How do I list all files of a directory?

我如何在Python中列出目录中的所有文件并将它们添加到list


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 :

from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

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

And lastly, as that example shows, adding one list to another you can either use .extend() or

>>> q = [1, 2, 3]
>>> w = [4, 5, 6]
>>> q = q + w
>>> q
[1, 2, 3, 4, 5, 6]

Personally, I prefer .extend()


I prefer using the glob module, as it does pattern matching and expansion.

import glob
print(glob.glob("/home/adam/*.txt"))

Will return a list with the queried files:

['/home/adam/file1.txt', '/home/adam/file2.txt', .... ]

import os
os.listdir("somedirectory")

将返回“somedirectory”中的所有文件和目录的列表。

链接地址: http://www.djcxy.com/p/448.html

上一篇: Markdown中的评论

下一篇: 如何列出目录的所有文件?