龙空技术网

获取文件夹中的文件列表

申浩黄粱 329

前言:

而今大家对“python如何读取一个文件夹下的所有文件”大概比较讲究,你们都需要学习一些“python如何读取一个文件夹下的所有文件”的相关资讯。那么小编也在网上搜集了一些关于“python如何读取一个文件夹下的所有文件””的相关知识,希望看官们能喜欢,各位老铁们一起来学习一下吧!

1. 现象

获取文件系统中某个目录下的所有文件列表

2. 原因分析无3. 问题解决

os.listdir函数来获取某个目录中的文件列表

import osprint(os.getcwd()) # 'E:\code\PythonCookBook\chapter4'os.chdir('..')print(os.getcwd()) # 'E:\code\PythonCookBook'print(os.listdir('./chapter4')) """['merged_file', 'py20210929.py', 'py20211010.py', 'py20211011.py', 'py20211012.py', 'py20211021.py', 'sorted_file_0', 'sorted_file_1', 'sorted_file_2', 'sorted_file_3', 'sorted_file_4', 'sorted_file_5']"""

os.listdir函数会返回目录中所有文件列表,包括所有文件,子目录,符号链接等等

如果需要通过某种方式过滤数据,可以考虑结合 os.path 库中的一些函数来使用列表推导

names = [name for name in os.listdir('./chapter4') if os.path.isfile(os.path.join('./chapter4', name))]dir_names = [name for name in os.listdir('./chapter4') if os.path.isdir(os.path.join('./chapter4', name))]

字符串的 startswith方法和 endswith方法对于过滤一个目录的内容也是很有用的

py_names = [name for name in os.listdir('./chapter4') if name.endswith('py')]"""['py20210929.py', 'py20211010.py', 'py20211011.py', 'py20211012.py', 'py20211021.py']"""

对于文件名的匹配,你可能会考虑使用 glob 或 fnmatch 模块

glob模块匹配特定模式的路径名称,使用Unix通配符规则

import glob# 相对路径py_pattern = glob.glob('./chapter4/*.py') # py_pattern 与 py_files 一致# 绝对路径py_ab_pattern = glob.glob('E:\code\PythonCookBook\chapter4\*.py') # py_ab_pattern 与 py_ab_files 一致py_files = [name for name in py_pattern]"""['./chapter4\\py20210929.py', './chapter4\\py20211010.py', './chapter4\\py20211011.py', './chapter4\\py20211012.py', './chapter4\\py20211021.py']"""py_ab_files = [name for name in py_ab_pattern]"""['E:\\code\\PythonCookBook\\chapter4\\py20210929.py', 'E:\\code\\PythonCookBook\\chapter4\\py20211010.py', 'E:\\code\\PythonCookBook\\chapter4\\py20211011.py', 'E:\\code\\PythonCookBook\\chapter4\\py20211012.py', 'E:\\code\\PythonCookBook\\chapter4\\py20211021.py']"""

fnmatch模块支持Unix shell格式的通配符

import fnmatchpy_files = [name for name in os.listdir('./chapter4') if fnmatch.fnmatch(name, '*.py')]"""<class 'list'>: ['py20210929.py', 'py20211010.py', 'py20211011.py', 'py20211012.py', 'py20211021.py']"""

获取目录中的列表是很容易的,但是其返回结果只是目录中实体名列表

如果需要获取其他的元信息,比如文件大小,修改时间等等,还需要使用到os.path模块中的函数或者os.stat函数来收集数据

import globimport timeimport ospy_pattern = glob.glob('./chapter4/*.py')py_meta = [(name, os.path.getsize(name), os.path.getmtime(name)) for name in py_pattern]for name, size, mtime in py_meta:    print(name, size, time.ctime(mtime))"""./chapter4\py20210929.py 1460 Sat Oct 9 22:14:52 2021./chapter4\py20211010.py 1663 Sun Oct 10 17:01:04 2021./chapter4\py20211011.py 1276 Mon Oct 11 22:07:16 2021./chapter4\py20211012.py 1902 Sat Oct 23 17:03:45 2021./chapter4\py20211021.py 2733 Sat Oct 23 21:42:16 2021"""print('####')file_meta = [(name, os.stat(name)) for name in py_pattern]for name, meta in file_meta:    print(name, meta.st_size, meta.st_mtime)"""./chapter4\py20210929.py 1460 1633788892.536979./chapter4\py20211010.py 1663 1633856464.6744094./chapter4\py20211011.py 1276 1633961236.9767005./chapter4\py20211012.py 1902 1634979825.0937288./chapter4\py20211021.py 2709 1634996395.330934"""

最后还有一点要注意的就是,有时候在处理文件名编码问题时候可能会出现一些问题。通常来讲,函数os.listdir函数返回的实体列表会根据系统默认的文件名编码来解码。有时候会碰到一些不能正常解码的文件名,需要我们进行特殊处理。

import osimport sysimport localeos.chdir('..')print(type('py\xf2x.txt')) # '<class 'str'>'print(sys.getdefaultencoding()) # 'utf-8'print(locale.getpreferredencoding()) # 'cp936'# encoding 默认编码 cp936 with open('py\xf2x.txt', 'w') as f_obj:    f_obj.write('Python!')print(os.listdir('.'))"""['.idea', 'chapter2', 'chapter3', 'chapter4', 'Chapter_1', 'data', 'main.py', 'models', 'notebooks', 'pyòx.txt', 'README.md', 'requirements.txt']"""print(os.listdir(b'.'))"""[b'.idea', b'chapter2', b'chapter3', b'chapter4', b'Chapter_1', b'data', b'main.py', b'models', b'notebooks', b'py\xc3\xb2x.txt', b'README.md', b'requirements.txt']"""with open(b'py\xc3\xb2x.txt', 'r') as f_obj:    print(f_obj.read())"""Python!"""
4. 错误经历无

标签: #python如何读取一个文件夹下的所有文件