Reputation: 33
I am trying to return the directory name as a string from every file that os.walk
finds, this is my code so far:
import os
def main():
path = '/Users/Documents/GitHub/files'
for dirpath, dirnames, filenames in os.walk(path):
for x in filenames:
print(os.path.dirname(os.path.abspath(x)))
if __name__ == "__main__":
main()
I understand that os.path.dirname()
and os.path.basename()
are the respective result of passing 'path' to os.path.split()
but why is the above not working when I use os.path.abspath()
?
Upvotes: 2
Views: 1155
Reputation: 9731
How about something like this, using a function of os.walk
and list comprehension?
def get_dirnames(path) -> list:
"""Return a list of directories from the root path.
Args:
path (str): Full path to the starting directory.
"""
dir_list = [os.path.join(root, d) for root, dirs, _ in os.walk(path) for d in dirs]
return dir_list
Which will output something like this, from your root path:
import os
path = 'c:/users/bob/documents'
get_dirnames(path)
['c:/users/bob/documents\\Doc_Excel',
'c:/users/bob/documents\\Doc_General',
'c:/users/bob/documents\\Doc_Music',
'c:/users/bob/documents\\Doc_PDF',
'c:/users/bob/documents\\Doc_PowerPoint'
...]
If this isn't what you're after, please provide an expected output and we'll see how we can help futher.
Upvotes: 0
Reputation: 1159
If I understand, you need to print every file while walking in directory? Your code walk with just printing in root, for me. Try out this and let me know if it helps you.
# Defined two function to print dir and file, then use for loop to walk in tree.
path = '/Users/Documents/GitHub/files'
def printfile(listdir, space):
for file in listdir:
print("/".rjust(space+1)+file)
def printdir(entrydir):
print(entrydir[0])
printfile(entrydir[2], len(entrydir[0]))
#wrap up
tree = os.walk(path)
for dir in tree:
printdir(dir)
Upvotes: 0
Reputation: 1977
Your code displays your current directory for each x
, because x
is just a filename (without its parent dir, which is stored in dirpath
). Why don't you simply print(dirpath)
?
If this doesn't answer your question, can you give the expected output?
Upvotes: 1
Reputation: 1654
Since you tagged the question as python 3.x, you might find pathlib
library useful.
from pathlib import Path
path = Path('/Users/Documents/GitHub/files')
for p in path.rglob("*"):
if p.is_file():
print(p.parent)
Upvotes: 2