Home > Back-end >  How to detect the full directory in Python?
How to detect the full directory in Python?

Time:01-23

I want to detect the full directory ( Like... C:/path/to/file.py? ) in [python]. And I don't really know what module to use, or something. So, let's imagine this function exists:

some.important.modules.checc()

If the Python file is somewhere in C:/Users/Rix/Downloads/Path/to/file.py, it would return C:/Users/Rix/Downloads/Path/to/file.py, or if the file is in C:/Users/Rix/Downloads/Some/very/interesting/path/to/file.py then it would return C:/Users/Rix/Downloads/Some/very/interesting/path/to/file.py.

So, what function could do like the some.important.modules.checc() function?

CodePudding user response:

To answer your question, this should works for you.

path = os.getcwd()
name = "tfc.qws"

for root, dirs, files in os.walk(path):
    if name in files:
        print(os.path.join(root, name))

The os.getcwd() provides the path to your current working directory (CWD). So, when you walk your path, the for loop will essentially loop through your directory to locate for the filename, name, you specified.

If the filename matches, then it prints out your CWD, concatenated with your filename, using os.path.join(root, name)

Clarification on Egemen İm's answer: I don't have enough reputation to make a "comment", the "\n" in Egemem İm answer means to have a new line printed before each of your path.

The sys module essentially provides a channel to modify the Python runtime environment; whereas sys.path does the following: enter image description here

With the "\n": enter image description here

  •  Tags:  
  • Related