Home > Software design >  Python, how to get the actual file location
Python, how to get the actual file location

Time:02-15

Using python 3: How do I get the path of my files? Please check the code below:

path =r'\\Desktop'
os.chdir(path)

for root, dirs, files in os.walk(path):
    for txt_file in files:
        if txt_file.endswith(".txt"):
            txt_fileSh=txt_file.rstrip(".txt")
            path_txt_file=os.path.abspath(txt_file)
            print(path_txt_file)

What I get is

\\Desktop\a.txt
\\Desktop\b.txt

... What I should get:

\\Desktop\Fig1\a.txt
\\Desktop\Fig2\b.txt

Help is very much appreciated.

CodePudding user response:

You don't need to change directory. You can build the full path based on the root of the walk as follows:

path = r'\Desktop'
import os

for root, _, files in os.walk(path):
    for file in files:
        if file.endswith('.txt'):
            print(os.path.join(root, file))

CodePudding user response:

The documentation for abspath states that:

os.path.abspath(path)

Return a normalized absolutized version of the pathname path. On most 
platforms, this is equivalent to calling the function normpath() as follows: 
normpath(join(os.getcwd(), path)).

So, you are actually just joining your path with the filename.

You want to use the path to the current directory instead, which is the first of the three items returned by os.walk, the one you named root.

So, just replace

path_txt_file=os.path.abspath(txt_file)

with

path_txt_file = os.path.join(root, txt_file)
  • Related