How do I get a list of all files (and directories) in a given directory in Python?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
The one worked with me is kind of a modified version from Saleh answer above.
The code is as follows:
"dir = 'given_directory_name' filenames = [os.path.abspath(os.path.join(dir,i)) for i in os.listdir(dir)]"
While
os.listdir()
is fine for generating a list of file and dir names, frequently you want to do more once you have those names - and in Python3, pathlib makes those other chores simple. Let's take a look and see if you like it as much as I do.To list dir contents, construct a Path object and grab the iterator:
If we want just a list of names of things:
If you want just the dirs:
If you want the names of all conf files in that tree:
If you want a list of conf files in the tree >= 1K:
Resolving relative paths become easy:
Navigating with a Path is pretty clear (although unexpected):
Try this:
You can use
For reference and more os functions look here:
A recursive implementation