import os # Define the path of a file file_path = "path/to/file.txt" # Get the directory of the file directory = os.path.dirname(file_path) # Print the directory print(directory)
To find the current directory of a file in Python, you can use the os.path.dirname() function from the os.path module. This function returns the directory part of a file path, without the file name. In our example, we first import the os.path module. Then, we define the path of a file and use the os.path.dirname() function to get the directory of the file. Finally, we print the directory to the console. The output should be the directory part of the file path, without the file name.
Alternatively, you can use the os.getcwd() function to get the current working directory of the Python interpreter. This is the directory that the Python interpreter was in when it was launched. Here is an example:
import os # Get the current working directory of the Python interpreter cwd = os.getcwd() # Print the current working directory print(cwd)In this example, we use the os.getcwd() function to get the current working directory of the Python interpreter. Then, we print the current working directory to the console.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.