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 usingos.chdir()To get the folder of the file, we can look at the docs of
os.walk():and
So in your case, try:
Also, check out the newer
Pathlibmodule