Set current dir in python

How to Set Current Working Directory in Python

To set the current working directory in Python, you can use the “os.chdir()” method. The os.chdir() method changes the current working directory to the given path. It returns None in all the other cases.

Example 1: How to Use os.chdir() Method

import os def current_working_dir(): print("Current working directory") print(os.getcwd(), "\n") current_working_dir() os.chdir("../../") print("After setting a new current directory", "\n") current_working_dir()
Current working directory /Users/krunallathiya/Desktop/Code/R After setting a new current directory Current working directory /Users/krunallathiya/Desktop/ 

In this example, we are first printing the current path in which this code file is located.

Then, using the os.chdir() function, we set the current path to a 2-level lower path.

Use the os.getcwd() function first, which shows the format of the accepted input for the os.chdir() function.

Example 2: Handling the errors while changing the directory

import sys import os # initial directory cwd = os.getcwd() # some non existing directory dr = 'false_dir/temp' # trying to insert to false directory try: print("Inserting inside-", os.getcwd()) os.chdir(dr) # Caching the exception except: print("Something wrong with specified directory. Exception- ") print(sys.exc_info()) # handling with finally finally: print() print("Restoring the path") os.chdir(cwd) print("Current directory is-", os.getcwd())
Inserting inside- /Users/krunallathiya/Desktop/Code/pythonenv/env Something wrong with specified directory. Exception- (, FileNotFoundError(2, 'No such file or directory'), ) Restoring the path Current directory is- /Users/krunallathiya/Desktop/Code/pythonenv/env 

Источник

Читайте также:  Https sed rostransnadzor ru login php

Python: Get and Change the Working Directory

Python Get and Set Current Working Directory Cover Image

In this tutorial, you’ll learn how to use Python to get and change (set) the working directory. Being able to work with the file system is a great skill to learn for a Python developer of any skill level. Being able to get and to change the working directory while in a Python script allows you to easily work with relative paths. This allows you to easily write paths to that are relative to the working directory.

By the end of this tutorial, you’ll have learned:

  • An overview of working with working directories using the Python os library
  • How to use the Python os library to get the working directory
  • How to change the working directory with Python
  • How to troubleshoot different error codes like NotADirectoryError or FileNotFoundError errors

Being able to work with and move around file systems is an important skill. This is especially true in data science where you may have directories for data, models, and scripts. Being able to traverse these directories without using paths fixed to a given computer allows you to build more flexible code that can move across computers.

The Quick Answer: Use os.getcwd() and os.chdir()

Quick Answer - Get and Change Working Directory Python

What is the Python os Library

The Python os module a built-in library allows us to perform common operating system tasks. Because the library is built into Python, you can easily import is directly, such as shown below:

# Importing the os Module import os

The module abstracts a number of helpful operating system operations. This is particularly helpful when developing scripts that are intended to work across different operating systems. The os module has a number of helpful functions. For example, it can be used to copy files using Python or to delete files using Python.

Python Get and Set Working Directory Snapshot

Get the Working Directory with Python OS

In this section, you’ll learn how to use the os library to get the current working directory in Python. By knowing the working directory, we can files in the directory by using relative paths. This allows us to build scripts that can easily move from one system to another, as long as the relative directory is the same.

We can use the Python os .getcwd() function to get the current working directory. getcwd stands for get current working directory.

Let’s see what this looks like:

# Get Current Working Directory with os.getcwd() import os cwd = os.getcwd() print('Current Working Directory is: ', cwd) # Returns: Current Working Directory is: /Users/datagy

The function doesn’t accept any arguments and returns a unicode representation of our current working directory. The format of the outputted directory will, of course, vary from operating system to operating system. In the above example, I’m running on a the script on a Mac OS computer. On a Windows computer, you may encounter a result such as C:\Users\datagy\Documents .

If you want to find the path to the file that is currently running your code (meaning you get the path to directory as well), you can use the os library as well. Simply assign os.path.realpath(__file__) to a variable and you can access it. The __file__ variable is used to identify the current file being imported.

Now that you know how to get the current working directory in Python, let’s see how we can use it change (or set) the working directory.

Change the Working Directory with Python OS

The Python os library comes with a helpful function that works similar to the getcwd() function. The chdir() function allows us to change the working directory. Unlike the getcwd() function, this function does accept a parameter and doesn’t return anything.

We can pass in either an absolute path or a relative path. Passing in an absolute path gives us the benefit of being explicit about where we want to change our working directory to. Using a relative path affords us the ability to reuse our script across different file systems, without knowing exactly where the script is running from.

Let’s see how the function works by using Python to change a working directory using an absolute path:

# Change the current working directory with os.chdir() import os cwd = os.getcwd() print('Current Working Directory is: ', cwd) absolute_path = '/Users/datagy/Documents' os.chdir(absolute_path) print('New working directory is: ', os.getcwd()) # Returns: # Current Working Directory is: /Users/datagy # New working directory is: /Users/datagy/Documents

The example above is a bit verbose: really, you just need to call os.chdir(absolute_path) . However, I wanted to illustrate how the changing of directories could work.

Now, let’s take a look at changing working directories using relative paths in Python. To move up a folder with a relative path you can simply use ../ , while moving down in the current directory involves simply adding that directory name into the script.

Let’s take a look at an example where we move down into a directory and then use relative paths to move back up:

# Change the current working directory with os.chdir() import os print('Current Working Directory is: ', os.getcwd()) # Move down a directory to 'Documents' os.chdir('Documents') # Confirm the current directory print('Current Working Directory is: ', os.getcwd()) # Use relative paths to move up a directory os.chdir('../') # Confirm the current directory print('Current Working Directory is: ', os.getcwd()) # Returns: # Current Working Directory is: /Users/datagy # Current Working Directory is: /Users/datagy/Documents # Current Working Directory is: /Users/datagy

We can see here that we used relative paths to move down a directory and then back up. This allows us to take this code from computer to computer – as long as the directory structure exists, the program will run without fail. Check out this tutorial to learn how to check if a file or directory exists in Python.

Handling Error Codes with Python OS

Working with file systems is never easy. There is plenty of room for typos to be made or user error that accidentally removes a directory that your code depends on. When changing a directory, the os.chdir() function expects a directory as its input. If, for example a file is passed in, then Python will raise a NotADirectoryError .

If you attempt to traverse the file system to a directory that doesn’t exist, then a FileNotFoundError (or an IOError ) is raised. If you do not have sufficient permissions to move into a directory, Python will raise a PermissionError .

Being aware of these errors codes and why they occur is an important process. It allows you to be more prepared in troubleshooting your programs and finding ways to solve your errors.

Conclusion

In this tutorial, you learned how to use Python to get a current working directory and how to use it to set a working directory. Being able to work with file systems and moving between directories allows you to built programs with growing complexity. This can be particularly important in data science when you’re working with directories that contains scripts and directories that contain data. It allows you to organize your files into logical directories that complement the set up of your program.

To learn more about the Python os library, check out the official documentation here.

Check out the articles below to learn about similar topics:

Источник

Get and change the current working directory in Python

In Python, you can get and change (set) the current working directory with os.getcwd() and os.chdir() . The os module is part of the standard library, so no additional installation is necessary, but you need to import it.

You can get the path of the current script file ( .py ) with __file__ . See the following article.

Get the current working directory: os.getcwd()

os.getcwd() returns the absolute path of the current working directory, where Python is running, as a string ( str ).

getcwd stands for «get current working directory», and the Unix command pwd stands for «print working directory». Of course, you can print the current working directory with os.getcwd() and print() .

import os path = os.getcwd() print(path) # /Users/mbp/Documents/my-project/python-snippets/notebook print(type(path)) # 

Use the os.path module to manipulate and handle path strings effectively. See the following article for details.

Change the current working directory: os.chdir()

You can change (set) the current working directory using os.chdir() .

Specify the target path as an argument, which can be either absolute or relative. Use ‘../’ to move up one directory level.

os.chdir() changes the current directory similar to the Unix command cd . Both chdir and cd stand for «change directory».

os.chdir('../') print(os.getcwd()) # /Users/mbp/Documents/my-project/python-snippets 

With the __file__ and os.path functions, you can change the current directory to the directory containing the running script file ( .py ).

os.chdir(os.path.dirname(os.path.abspath(__file__))) 

See the following article for details.

  • Create a directory with mkdir(), makedirs() in Python
  • Read, write, and create files in Python (with and open())
  • Get the path of current file (script) in Python: __file__
  • Check if a file or a directory exists in Python
  • Zip and unzip files with zipfile and shutil in Python
  • Get the filename, directory, extension from a path string in Python
  • Get the size of a file and directory in Python
  • NumPy: Determine if ndarray is view or copy and if it shares memory
  • Check pandas version: pd.show_versions
  • Detect and read barcodes and QR codes with ZBar in Python
  • Shallow and deep copy in Python: copy(), deepcopy()
  • pandas: Replace missing values (NaN) with fillna()
  • Calculate cumulative sum and product in Python (itertools.accumulate)
  • Right-justify, center, left-justify strings and numbers in Python
  • List comprehensions in Python

Источник

Оцените статью