专业编程基础技术教程

网站首页 > 基础教程 正文

获取文件夹中的文件列表

ccvgpt 2024-08-11 15:04:00 基础教程 9 ℃

1. 现象

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

2. 原因分析

3. 问题解决

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

获取文件夹中的文件列表

import os


print(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 fnmatch
py_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 glob
import time
import os


py_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 os
import sys
import locale


os.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. 错误经历

Tags:

最近发表
标签列表