要列出目录下所有文件,最直接的方法是使用os.listdir()函数。该函数返回指定路径下所有文件和子目录的名称列表,但仅限当前层级,不递归子目录。结合os.path.isfile()可区分文件与目录,通过os.path.join()获取完整路径。为处理权限或路径不存在等问题,需使用try-except捕获FileNotFoundError和PermissionError异常。若需递归遍历所有子目录,推荐使用os.walk(),它自动生成目录树中每个层级的(root, dirs, files)三元组,便于深度遍历。对于按模式筛选文件的需求,可用glob模块支持通配符匹配,如.txt,并通过recursive=True配合*实现递归搜索。此外,可结合os.listdir与列表推导式实现自定义筛选逻辑。在实际操作中,应始终使用os.path.join()构建跨平台兼容的路径,并妥善处理各类异常以提升程序健壮性。

在Python中,要列出目录下的所有文件,最直接且常用的方法是利用内置的
os
os.listdir()
要列出Python中一个目录下的所有文件,你可以使用
os.listdir()
os.path
import os
def list_files_in_directory(path):
"""
列出指定目录下所有文件和子目录的名称。
"""
try:
entries = os.listdir(path)
print(f"目录 '{path}' 下的内容:")
for entry in entries:
full_path = os.path.join(path, entry)
if os.path.isfile(full_path):
print(f" 文件: {entry}")
elif os.path.isdir(full_path):
print(f" 目录: {entry}")
else:
print(f" 其他: {entry}")
return entries
except FileNotFoundError:
print(f"错误: 目录 '{path}' 不存在。")
return []
except PermissionError:
print(f"错误: 没有权限访问目录 '{path}'。")
return []
# 示例使用
# 假设当前目录下有一个名为 'my_folder' 的文件夹
# 你也可以替换成你自己的路径,比如 '/Users/yourname/Documents'
current_directory = os.getcwd() # 获取当前工作目录
# 创建一个测试目录和文件,如果它们不存在的话
test_dir = os.path.join(current_directory, "test_listing_dir")
if not os.path.exists(test_dir):
os.makedirs(test_dir)
with open(os.path.join(test_dir, "file1.txt"), "w") as f:
f.write("hello")
with open(os.path.join(test_dir, "file2.py"), "w") as f:
f.write("import os")
os.makedirs(os.path.join(test_dir, "subdir"))
list_files_in_directory(test_dir)仅仅列出当前目录的文件往往不够,很多时候我们需要深入到所有子目录中,把所有文件都找出来。这时,
os.walk()
os.walk()
root
dirs
files
root
dirs
root
files
root
import os
def list_all_files_recursively(start_path):
"""
递归地列出指定路径下所有文件(包括子目录中的文件)的完整路径。
"""
print(f"\n递归列出 '{start_path}' 下的所有文件:")
all_files = []
try:
for root, dirs, files in os.walk(start_path):
# root: 当前正在遍历的目录路径
# dirs: root 下的子目录名称列表
# files: root 下的文件名称列表
for file_name in files:
full_file_path = os.path.join(root, file_name)
all_files.append(full_file_path)
print(f" {full_file_path}")
return all_files
except FileNotFoundError:
print(f"错误: 起始目录 '{start_path}' 不存在。")
return []
except PermissionError:
print(f"错误: 没有权限访问起始目录 '{start_path}'。")
return []
# 示例使用
list_all_files_recursively(test_dir)
# 可以在 test_dir/subdir 中再创建一些文件来测试递归效果
if os.path.exists(os.path.join(test_dir, "subdir")):
with open(os.path.join(test_dir, "subdir", "nested_file.txt"), "w") as f:
f.write("nested content")
print("\n--- 添加嵌套文件后再次遍历 ---")
list_all_files_recursively(test_dir)os.walk()
os.listdir()
os.path.isdir()
立即学习“Python免费学习笔记(深入)”;
很多时候,我们需要的不是目录下的所有文件,而是那些符合特定条件的文件,比如所有
.txt
glob
glob
import glob
import os
def filter_files_by_pattern(directory_path, pattern):
"""
根据给定的模式筛选目录中的文件。
"""
# glob.glob() 可以接受相对路径或绝对路径
# 这里的 pattern 会匹配 directory_path 下的文件
# '**' 可以用于递归匹配子目录 (需要 glob 模块版本 >= 3.5 并且设置 recursive=True)
search_pattern = os.path.join(directory_path, pattern)
print(f"\n在 '{directory_path}' 中搜索模式 '{pattern}' 的文件:")
try:
# glob.glob 默认不递归,要递归需要加 recursive=True
# 如果 pattern 中包含 '**',则需要 recursive=True
if '**' in pattern:
matching_files = glob.glob(search_pattern, recursive=True)
else:
matching_files = glob.glob(search_pattern)
if matching_files:
for file_path in matching_files:
print(f" 匹配文件: {file_path}")
else:
print(" 没有找到匹配的文件。")
return matching_files
except Exception as e:
print(f"错误在筛选文件时发生: {e}")
return []
# 示例使用
# 筛选 .txt 文件
filter_files_by_pattern(test_dir, "*.txt")
# 筛选 .py 文件
filter_files_by_pattern(test_dir, "*.py")
# 筛选所有文件 (等同于 os.listdir,但返回完整路径)
filter_files_by_pattern(test_dir, "*")
# 递归筛选所有 .txt 文件 (需要 Python 3.5+ 和 recursive=True)
# 注意:glob.glob 默认不递归,需要显式指定 recursive=True
# 模式中的 '**' 表示匹配任意目录和子目录
filter_files_by_pattern(test_dir, "**/*.txt")
# 如果 glob 不足以满足需求,你也可以结合 os.listdir 和列表推导式进行更复杂的筛选
def custom_filter_files(directory_path, starts_with=None, ends_with=None):
print(f"\n自定义筛选 '{directory_path}' 中的文件 (前缀: {starts_with}, 后缀: {ends_with}):")
filtered_files = []
try:
for entry in os.listdir(directory_path):
full_path = os.path.join(directory_path, entry)
if os.path.isfile(full_path):
match = True
if starts_with and not entry.startswith(starts_with):
match = False
if ends_with and not entry.endswith(ends_with):
match = False
if match:
filtered_files.append(full_path)
print(f" 匹配文件: {full_path}")
return filtered_files
except FileNotFoundError:
print(f"错误: 目录 '{directory_path}' 不存在。")
return []
except PermissionError:
print(f"错误: 没有权限访问目录 '{directory_path}'。")
return []
custom_filter_files(test_dir, ends_with=".py")
custom_filter_files(test_dir, starts_with="file")glob
*
?
[]
**
recursive=True
os.listdir
os.path.getsize()
os.path.getmtime()
仅仅获取文件名通常是不够的,我们还需要文件的完整路径才能进行后续的读写、移动等操作。另外,在处理文件系统时,权限问题总是防不胜防,如果不加处理,程序很可能就直接崩溃了。我通常会把获取完整路径和错误处理这两个环节视为文件操作的“标配”。
import os
def get_full_paths_and_handle_errors(directory_path):
"""
获取目录下所有文件的完整路径,并处理常见的错误。
"""
print(f"\n处理 '{directory_path}' 中的文件(获取完整路径及错误处理):")
full_paths = []
try:
for entry_name in os.listdir(directory_path):
full_path = os.path.join(directory_path, entry_name)
# 区分文件和目录,只处理文件
if os.path.isfile(full_path):
full_paths.append(full_path)
print(f" 文件完整路径: {full_path}")
elif os.path.isdir(full_path):
print(f" 发现子目录(跳过文件处理): {full_path}")
else:
print(f" 发现其他类型条目: {full_path}")
return full_paths
except FileNotFoundError:
print(f"错误: 目录 '{directory_path}' 不存在。请检查路径是否正确。")
return []
except PermissionError:
print(f"错误: 没有权限访问目录 '{directory_path}'。请检查权限设置。")
return []
except Exception as e:
print(f"发生未知错误: {e}")
return []
# 示例使用
get_full_paths_and_handle_errors(test_dir)
# 尝试访问一个不存在的目录
get_full_paths_and_handle_errors("/nonexistent/path/to/test")
# 假设有一个你没有权限访问的目录 (这里无法直接模拟,但代码结构展示了处理方式)
# 例如:get_full_paths_and_handle_errors("/root") # 在非root用户下可能会触发 PermissionErroros.path.join()
\
/
os.path.isfile()
至于错误处理,
try-except
FileNotFoundError
PermissionError
Exception
Exception
以上就是python中怎么列出目录下的所有文件?的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号