0

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?

Kofi
  • 1,224
  • 1
  • 10
  • 21
Niek
  • 51
  • 8
  • Because "the path it's currently looking at" has **nothing to do with** the current working directory, and there's **no reason** why it should be expected to. The traversal doesn't work by changing the process CWD; it works by asking the system what's in those folders. – Karl Knechtel Mar 15 '23 at 09:01

2 Answers2

2

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

1

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)