Reputation: 11
It's my first time working in Python, and I'm having a bit of trouble finding the intermediate directory path in the following segment of code:
Currently, when passing a directory argument to 'stroll', the function seems to enter thePath, observing each subdirectory type, and descending if of type directory. The code isn't mine, and it seems that the nested for loop is iterating over a list of regular files, so the loop wouldn't know anything about the directory to which each element belongs.
Current output is
../Sample_Cases_Asg2/output.txt
../Sample_Cases_Asg2/file2
../Sample_Cases_Asg2/file1
../Sample_Cases_Asg2/output.txt
../Sample_Cases_Asg2/file2
../Sample_Cases_Asg2/file1
../Sample_Cases_Asg2/output.txt
../Sample_Cases_Asg2/file2
../Sample_Cases_Asg2/file1
../Sample_Cases_Asg2/output.txt
../Sample_Cases_Asg2/file2
../Sample_Cases_Asg2/file1
Desired output is
../Sample_Cases_Asg2/sample1/output.txt
../Sample_Cases_Asg2/sample1/file2
../Sample_Cases_Asg2/sample1/file1
../Sample_Cases_Asg2/sample2/output.txt
../Sample_Cases_Asg2/sample2/file2
../Sample_Cases_Asg2/sample2/file1
../Sample_Cases_Asg2/sample3output.txt
../Sample_Cases_Asg2/sample3/file2
../Sample_Cases_Asg2/sample3/file1
../Sample_Cases_Asg2/sample3/output.txt
../Sample_Cases_Asg2/sample3/file2
../Sample_Cases_Asg2/sample3/file1
The implementation is
def stroll(thePath):
deeper = []
for root, dirs, files in os.walk(thePath):
for file in files:
print (os.path.join(thePath, file))
Additionally, I'm new to the community so any concise input on how to improve my question asking would be greatly appreciated.
Upvotes: 1
Views: 34
Reputation: 36013
If you put help(os.walk)
in a shell, you will see:
For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), yields a 3-tuple
dirpath, dirnames, filenames
dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists are just names, with no path components.
So you need:
os.path.join(root, file)
It's pretty annoying.
Upvotes: 1