How to Find the Current Working Directory and File Directory in Python?

python

In Python, you can use the os module to find the current working directory and file directory.

To find the current working directory, you can use the os.getcwd() function:

import os

cwd = os.getcwd()
print(cwd)

This will print the absolute path of the current working directory.

To find the file directory of the current script, you can use the os.path.dirname(__file__) function:

import os

file_dir = os.path.dirname(__file__)
print(file_dir)

This will print the absolute path of the directory where the current script is located. Note that __file__ is a special variable in Python that contains the path of the current script.

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?