简体   繁体   中英

Python - os.getcwd() doesn't return the full path

At the start of the file, I specified the path using:

path = r"C:\Documents\Data"
os.chdir(path)

Later on, I want to iterate through subfolders in the Data folder. This folder contains 2018 , which contains Level2A . I do this with:

for root, subdirectories, files in os.walk(path):
        for filename in subdirectories:
            if filename.endswith('.SAFE'):
                print(filename)
                print(os.getcwd())

When printing the subfolder's name, it works; it prints folder_name.SAFE . When I, however want to print the path which it's currently looking at, I get the following:

print(os.getcwd())
>>> C:\Documents\Data

Why do I not get C:\Documents\Data\2018\Level2A whose file I printed is? What do I have to change to do get this?

os.getcwd() returns the current working directory and that is the directory you changed into using os.chdir()

To get the folder of the file, we can look at the docs of os.walk() :

it yields a 3-tuple (dirpath, dirnames, filenames)

and

To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).

So in your case, try:

print(os.path.join(root, filename))

Also, check out the newer Pathlib module

everytime you exceute os.getcwd(), you will get your current directory. if you need full path of filename that contain ".SAFE" on it's filename, you need to print something like this:

for root, subdirectories, files in os.walk(path):
    for filename in subdirectories:
        if filename.endswith('.SAFE'):
            print(filename)
            print(root+"/"+filename)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM