Python current directory script

How to get current directory in Python?

In this article, we will take a look at how to get current directory in Python. The current directory is nothing but your working directory from which your script is getting executed.

Getting the Current Working Directory in Python

The os module has a getcwd() function using which we can find out the absolute path of the working directory.

Syntax: os.getcwd()

Parameter: None

Return Value: Returns the string which contains the absolute path of the current working directory.

Below is an example to print the current working directory in Python

# Python program get current working directory using os.getcwd() # importing os module import os # Get the current directory path current_directory = os.getcwd() # Print the current working directory print("Current working directory:", current_directory) 
Current working directory: C:\Projects\Tryouts

Get the path of the script file in Python

If you want to get the path of the current script file, you could use a variable __file__ and pass it to the realpath method of the os.path module.

Читайте также:  Java sql sqlexception cannot

Example to get the path of the current script file

# Python program get current working directory using os.getcwd() # importing os module import os # Get the current directory path current_directory = os.getcwd() # Print the current working directory print("Current working directory:", current_directory) # Get the script path and the file name foldername = os.path.basename(current_directory) scriptpath = os.path.realpath(__file__) # Print the script file absolute path print("Script file path is : " + scriptpath)
Current working directory: C:\Projects\Tryouts Script path is : C:\Projects\Tryouts\main.py

Changing the Current Working Directory in Python

If you want to change the current working directory in Python, use the chrdir() method.

Syntax: os.chdir(path)

path: The path of the new directory in the string format.

Returns: Doesn’t return any value

Example to change the current working directory in Python

# Import the os module import os # Print the current working directory print("Current working directory: ".format(os.getcwd())) # Change the current working directory os.chdir('/Projects') # Print the current working directory print("New Current working directory: ".format(os.getcwd())) 
Current working directory: C:\Projects\Tryouts New Current working directory: C:\Projects

Conclusion

To get the current working directory in Python, use the os module function os.getcwd() , and if you want to change the current directory, use the os.chrdir() method.

Источник

Python 3: Path of the Current Script File and Directory

If you want the path of the directory that the current Python script file is in:

from pathlib import Path script_dir = Path( __file__ ).parent.absolute() print( script_dir )

Using os.path

File Path

To get the file path of the current Python script:

import os script_path = os.path.abspath( __file__ ) print( script_path )

Directory

If you want the path of the directory that the current Python script file is in:

import os script_dir = os.path.abspath( os.path.dirname( __file__ ) ) print( script_dir )

__file__

__file__ is an attribute (special variable) set by Python in modules that are loaded from files (usually, but not required to be, files that have the .py extension). The attribute is not set when you’re running code inside a Python shell (the python or python3 command line program), in a Jupyter notebook, or in other cases where the module is not loaded from a file.

Although we could use __file__ by itself:

it is not guaranteed to be an absolute path (i.e., it may be a relative path). The pathlib.Path.absolute() or os.path.abspath call ensures that it is an absolute path.

References and Notes

  • The import system — Python 3 documentation
  • In Python 3.4 and up, __file__ is always an absolute path «by default, with the sole exception of __main__.__file__ when a script has been executed directly using a relative path.» See Other Language Changes — What’s New in Python 3.4.

Источник

How to Get Current Working Directory in Python

The file or folder name can be used with the full path or just mentioning the file or folder name only to use it in the script. The full path of a file or folder from the root directory is specified by absolute path. When the file name is used without the pathname in the script, then the Current Working Directory is assumed as the file’s pathname and is called the relative path. In Python, the Current Working Directory is set to the directory location from where the python script executes. Many modules exist in python to get the Current Working Directory. The ways to retrieve the Current Working Directory by using different modules in Python have shown in this tutorial.

Example-1: Using pathlib module to get Current Working Directory

The path class of the pathlib module is used to read the current working directory of the executing script. Create a python script with the following code to read and print the current working directory using the pathlib module. The cwd() method of the Path class is used to print the current working directory from where the script is executing.

# Import the Path from pathlib module

# Retrieve the path of current working directory

current_working_directory = Path. cwd ( )

# Print the location of current working directory

print ( «The location of the current working directory is:» )

Output:

The following output will appear after executing the above script. Here, the path of the current working directory without the script name has shown in the output.

Example-2: Using normpath() and abspath() to get the Current Working Directory

Using the os module is another way to retrieve the current working directory. Different methods exist in the path class of the os module to retrieve the current working directory. The normpath() and abspath() methods are the two of them. These methods return the current working directory as a string. Create a python file with the following script to check the purposes of these functions.

# Print the current working directory using normpath() function

print ( «The current working directory (using normpath()) is:» )

print ( os . path . dirname ( os . path . normpath ( __file__ ) ) )

# Print the current working directory using abspath() function

print ( » \n The current working directory (using abspath()) is:» )

Output:

The following output will appear after executing the above script. Here, the path of the current working directory without the script name has shown in the output.

Example-3: Using realpath() to get the Current Working Directory

The realpath() is another method to retrieve the current working directory. Create a python file with the following script to print the current working directory with the script name by using the realpath() method. In the script, it takes the __file__ as the argument value containing the file’s pathname in which the os module is imported.

# Read the current working directory using realpath() function

real_path = os . path . realpath ( __file__ )

# Print the current working directory with the script name

print ( » \n The current working directory with the script name is:» )

Output:

The following output will appear after executing the above script. Here, the path of the current working directory with the script name has shown in the output.

Example-4: Using getcwd() to get the Current Working Directory

Using the getcwd() function of the os module is the most simple way to retrieve the current working directory of the executing script. It does not contain any argument and returns the CWD as a string. Create a python file with the following script to check the use of the getcwd() function. The current working directory is printed at the beginning of the script. Next, the current directory path is changed by using the chdir() function. The getcwd() command is called again after changing the directory.

# Print the current working directory using getcwd() function

print ( «The current working directory is: \n » , os . getcwd ( ) )

# Change the current working directory

# Print the current working directory after change

print ( » \n The current working directory after change is: \n » , os . getcwd ( ) )

Output:

The following output will appear after executing the above script. Here, the current working directory path without the script name has been printed before changing the directory. Next, the changed directory path has been printed.

Example-5: Using getcwd() with try-except to get the Current Working Directory

Create a python file with the following script to change the current working directory based on the input value and handle different types of errors. Three types of errors can be handled by executing the script. The FileNotFoundError error will be generated if the path taken from the input does not exist. The NotADirectoryError error will be generated if the path taken from the input is not a directory. The PermissionError error will be generated if the path taken from the input is not accessible.

# Enter the path of the directory

cwd = input ( «Enter the path of current working directory: \n » )

# Change the current working directory

# Print the current working directory using getcwd() function

print ( «The current working directory is: \n » , os . getcwd ( ) )

# Raise error if the directory does not exist

print ( «Directory does not exist.» )

# Raise error if the input path is not a directory

print ( «%s is not a directory» % ( cwd ) )

# Raise error if the directory is not accessible

print ( «Permission denied to change the directory.» )

Output:

The following output will appear after executing the above script if the path exists. Here, the taken input path exists, and the changed working directory has printed in the output.

The following output will appear after executing the above script if the path does not exist.

The following output will appear after executing the above script if the taken path is not accessible.

Conclusion:

The use of pathlib and os modules to read the current working directory is shown in this tutorial by using different examples. The way to retrieve the current working directory after changing the current working directory based on user input has also been shown in this tutorial.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Get the Current Script File Directory in Python

Get the Current Script File Directory in Python

  1. Python Get the Working Directory
  2. Python Get the Script File Directory

We have introduced the file and directory operation in Python 3 basic tutorial. In this section, we show you how to get the relative and absolute path of the executing script.

Python Get the Working Directory

os.getcwd() function returns the current working directory.

If you run it in Python idle prompt, the result is the path of Python IDLE.

Python Get the Script File Directory

The script file path could be found in the global namespace with the special global variable __file__ . It returns the relative path of the script file relative to the working directory.

We will show you in the below example codes how to use the functions we just introduced.

import os  wd = os.getcwd() print("working directory is ", wd)  filePath = __file__ print("This script file path is ", filePath)  absFilePath = os.path.abspath(__file__) print("This script absolute path is ", absFilePath)  path, filename = os.path.split(absFilePath) print("Script file path is <>, filename is <>".format(path, filename)) 
absFilePath = os.path.abspath(__file__) 

os.path.abspath(__file__) returns the absolute path of the given relative path.

path, filename = os.path.split(absFilePath) 

The os.path.split() method splits the file name with path to pure path and pure file name.

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

Источник

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