Niek
Niek

Reputation: 51

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?

Upvotes: 0

Views: 2566

Answers (2)

mohamadsajedi
mohamadsajedi

Reputation: 21

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)

Upvotes: 1

my_display_name
my_display_name

Reputation: 123

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

Upvotes: 2

Related Questions