如何列出目录中的所有文件?

3466 投票
21 回答
8218265 浏览
提问于 2025-04-16 01:00

我想知道怎么用Python列出一个文件夹里的所有文件,并把它们放到一个list里。

21 个回答

1566

列出当前目录中的文件

使用 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)

或者

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 会返回根目录、目录列表和文件列表,所以我在循环中把它们分别解包成 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 和 walk 只获取目录,因为在 [1] 元素中只有文件夹

 import os
 next(os.walk('F://python'))[1] # for the current dir use ('.')
 
 >>> ['python3','others']

使用 walk 获取所有的 subdir 名称

for r,d,f in os.walk("F:\\_python"):
    for dirs in d:
        print(dirs)

os.scandir() 从 Python 3.5 及更高版本开始可用

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)
2562

我更喜欢使用glob模块,因为它可以进行模式匹配和扩展。

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

它的模式匹配非常直观。

import glob
# All files and directories ending with .txt and that don't begin with a dot:
print(glob.glob("/home/adam/*.txt")) 
# All files and directories ending with .txt with depth of 2 folders, ignoring names beginning with a dot:
print(glob.glob("/home/adam/*/*.txt")) 

它会返回一个包含你查询的文件和目录的列表:

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

需要注意的是,glob会忽略以点.开头的文件和目录,因为这些被认为是隐藏的文件和目录,除非你的模式是像.*这样的。

使用glob.escape来处理那些不想作为模式的字符串:

print(glob.glob(glob.escape(directory_name) + "/*.txt"))
6386

os.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

撰写回答