I have such file structure:
d:\temp\random1\index.html
d:\temp\random2\index.html
d:\temp\random3\index.html
and I want to get paths to list in python. So the output would be:
files = ['path': 'd:\temp\random1\index.html', 'directory': 'random1']
I am using such code:
files = []
for dirpath, dirnames, filenames in os.walk('D:\\temp'):
for fname in filenames:
if fname.endswith(".md"):
path = os.path.join(dirpath,fname)
files.append({'path':path,'directory': dirpath})
but I cannot figure out how to get directory values.All I get with this code is:
files = ['path': 'd:\temp\random1\index.html', 'directory': 'd:\temp\random1\']
How to get the directory without some dirty hacks?
walk() work in python ? OS. walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). root : Prints out directories only from what you specified.
The Python os. listdir() method returns a list of every file and folder in a directory. os. walk() function returns a list of every file in an entire file tree.
Walking a filesystem means recursively visiting a directory and any sub-directories. It is a fairly common requirement for copying, searching etc.
listdir() method in python is used to get the list of all files and directories in the specified directory.
Try
dirname = dirpath.split(os.path.sep)[-1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With