如何在Python中列出目录中的所有文件并将其添加到列表中?
当前回答
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
其他回答
仅获取文件列表(无子目录)的单行解决方案:
filenames = next(os.walk(path))[2]
或绝对路径名:
paths = [os.path.join(path, fn) for fn in next(os.walk(path))[2]]
一位聪明的老师曾经告诉我:
当有几种既定的方法来做某事时,没有一种方法对所有情况都有好处。
因此,我将为问题的一个子集添加一个解决方案:通常,我们只想检查文件是否匹配开始字符串和结束字符串,而不需要进入子目录。因此,我们需要一个返回文件名列表的函数,例如:
filenames = dir_filter('foo/baz', radical='radical', extension='.txt')
如果您想首先声明两个函数,可以这样做:
def file_filter(filename, radical='', extension=''):
"Check if a filename matches a radical and extension"
if not filename:
return False
filename = filename.strip()
return(filename.startswith(radical) and filename.endswith(extension))
def dir_filter(dirname='', radical='', extension=''):
"Filter filenames in directory according to radical and extension"
if not dirname:
dirname = '.'
return [filename for filename in os.listdir(dirname)
if file_filter(filename, radical, extension)]
这个解决方案可以很容易地用正则表达式来概括(如果您不希望模式总是停留在文件名的开头或结尾,您可能需要添加一个模式参数)。
当前目录中的列表
使用os模块中的listdir,可以获得当前目录中的文件和文件夹
import os
arr = os.listdir()
查找目录
arr = os.listdir('c:\\files')
使用glob,可以指定要列出的文件类型,如下所示
import glob
txtfiles = []
for file in glob.glob("*.txt"):
txtfiles.append(file)
or
mylist = [f for f in glob.glob("*.txt")]
仅获取当前目录中文件的完整路径
import os
from os import listdir
from os.path import isfile, join
cwd = os.getcwd()
onlyfiles = [os.path.join(cwd, f) for f in os.listdir(cwd) if
os.path.isfile(os.path.join(cwd, f))]
print(onlyfiles)
['G:\\getfilesname\\getfilesname.py', 'G:\\getfilesname\\example.txt']
使用os.path.abspath获取完整路径名
你得到了完整的路径作为回报
import os
files_path = [os.path.abspath(x) for x in os.listdir()]
print(files_path)
['F:\\documenti\applications.txt', 'F:\\documenti\collections.txt']
漫游:遍历子目录
os.walk返回根目录、目录列表和文件列表,这就是为什么我在for循环中在r、d、f中解压缩它们;然后,它在根目录的子文件夹中查找其他文件和目录,依此类推,直到没有子文件夹为止。
import os
# Getting the current work directory (cwd)
thisdir = os.getcwd()
# r=root, d=directories, f = files
for r, d, f in os.walk(thisdir):
for file in f:
if file.endswith(".docx"):
print(os.path.join(r, file))
在目录树中向上
# Method 1
x = os.listdir('..')
# Method 2
x= os.listdir('/')
使用os.listdir()获取特定子目录的文件
import os
x = os.listdir("./content")
os.walk('.')-当前目录
import os
arr = next(os.walk('.'))[2]
print(arr)
>>> ['5bs_Turismo1.pdf', '5bs_Turismo1.pptx', 'esperienza.txt']
next(os.walk('.'))和os.path.join('dir','file')
import os
arr = []
for d,r,f in next(os.walk("F:\\_python")):
for file in f:
arr.append(os.path.join(r,file))
for f in arr:
print(files)
>>> F:\\_python\\dict_class.py
>>> F:\\_python\\programmi.txt
下一个步行
[os.path.join(r,file) for r,d,f in next(os.walk("F:\\_python")) for file in f]
>>> ['F:\\_python\\dict_class.py', 'F:\\_python\\programmi.txt']
os.walk
x = [os.path.join(r,file) for r,d,f in os.walk("F:\\_python") for file in f]
print(x)
>>> ['F:\\_python\\dict.py', 'F:\\_python\\progr.txt', 'F:\\_python\\readl.py']
os.listdir()-仅获取txt文件
arr_txt = [x for x in os.listdir() if x.endswith(".txt")]
使用glob获取文件的完整路径
from path import path
from glob import glob
x = [path(f).abspath() for f in glob("F:\\*.txt")]
使用os.path.isfile避免列表中的目录
import os.path
listOfFiles = [f for f in os.listdir() if os.path.isfile(f)]
使用Python 3.4中的pathlib
import pathlib
flist = []
for p in pathlib.Path('.').iterdir():
if p.is_file():
print(p)
flist.append(p)
通过列表理解:
flist = [p for p in pathlib.Path('.').iterdir() if p.is_file()]
在pathlib.Path()中使用glob方法
import pathlib
py = pathlib.Path().glob("*.py")
使用os.walk获取所有文件:仅检查返回的第三个元素,即文件列表
import os
x = [i[2] for i in os.walk('.')]
y=[]
for t in x:
for f in t:
y.append(f)
仅获取目录中带有next的文件:仅返回根文件夹中的文件
import os
x = next(os.walk('F://python'))[2]
使用next只获取目录并在目录中行走,因为在[1]元素中只有文件夹
import os
next(os.walk('F://python'))[1] # for the current dir use ('.')
>>> ['python3','others']
使用walk获取所有分区名称
for r,d,f in os.walk("F:\\_python"):
for dirs in d:
print(dirs)
Python 3.5及更高版本的os.scandir()
import os
x = [f.name for f in os.scandir() if f.is_file()]
# Another example with `scandir` (a little variation from docs.python.org)
# This one is more efficient than `os.listdir`.
# In this case, it shows the files only in the current directory
# where the script is executed.
import os
with os.scandir() as i:
for entry in i:
if entry.is_file():
print(entry.name)
返回绝对文件路径列表,不会递归到子目录
L = [os.path.join(os.getcwd(),f) for f in os.listdir('.') if os.path.isfile(os.path.join(os.getcwd(),f))]
我将提供一个示例单行,其中可以提供源路径和文件类型作为输入。代码返回带有csv扩展名的文件名列表。使用以防需要返回所有文件。这还将递归扫描子目录。
[y代表os.walk中的x(sourcePath)代表glob中的y(os.path.join(x[0],'*.csv'))]
根据需要修改文件扩展名和源路径。