如何在Python中列出目录中的所有文件并将其添加到列表中?


当前回答

def list_files(path):
    # returns a list of names (with extension, without full path) of all files 
    # in folder path
    files = []
    for name in os.listdir(path):
        if os.path.isfile(os.path.join(path, name)):
            files.append(name)
    return files 

其他回答

dircache是“自2.6版以来已弃用:Python 3.0中已删除dircache模块。”

import dircache
list = dircache.listdir(pathname)
i = 0
check = len(list[0])
temp = []
count = len(list)
while count != 0:
  if len(list[i]) != check:
     temp.append(list[i-1])
     check = len(list[i])
  else:
    i = i + 1
    count = count - 1

print temp

listdir()返回目录中的所有内容——包括文件和目录。

os.path的isfile()只能用于列出文件:

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

或者,os.walk()为它访问的每个目录生成两个列表——一个用于文件,一个用于目录。如果您只想要顶级目录,则可以在第一次生成时中断:

from os import walk

f = []
for (dirpath, dirnames, filenames) in walk(mypath):
    f.extend(filenames)
    break

或更短:

from os import walk

filenames = next(walk(mypath), (None, None, []))[2]  # [] if no file
import os
os.listdir("somedirectory")

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

def list_files(path):
    # returns a list of names (with extension, without full path) of all files 
    # in folder path
    files = []
    for name in os.listdir(path):
        if os.path.isfile(os.path.join(path, name)):
            files.append(name)
    return files 

我将提供一个示例单行,其中可以提供源路径和文件类型作为输入。代码返回带有csv扩展名的文件名列表。使用以防需要返回所有文件。这还将递归扫描子目录。

[y代表os.walk中的x(sourcePath)代表glob中的y(os.path.join(x[0],'*.csv'))]

根据需要修改文件扩展名和源路径。