Question
How can I list all files of a directory in python and add them to a list?
How-To
os.listdir() will get you everything that's in a directory - files and directories. If you want just files, you could either filter this down using os.path:
or you could use os.walk() which will yield two lists for each directory it visits - splitting into files and dirs for you. If you only want the top directory you can just break the first time it yields:
- from os import walk
- f = []
- for (dirpath, dirnames, filenames) in walk(mypath):
- f.extend(filenames)
- break
* [ Python 文章收集 ] 常見檔案操作範例
沒有留言:
張貼留言