要列出目录下所有文件,最直接的方法是使用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 osdef 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 osdef 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
文件,或者以特定前缀命名的文件。这时,Python的
glob
模块就显得非常实用了,它支持Unix shell风格的路径名模式扩展。我个人觉得
glob
在处理这类需求时,比手动编写循环和字符串匹配要优雅得多。
import globimport osdef 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 osdef 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用户下可能会触发 PermissionError
os.path.join()
函数是构建文件路径的关键,它能智能地根据操作系统的不同(Windows使用
,Linux/macOS使用
/
)来拼接路径,避免了手动字符串拼接可能导致的兼容性问题。同时,使用
os.path.isfile()
来判断一个路径是否指向文件,可以帮助我们精确地筛选出需要处理的对象。
至于错误处理,
try-except
块是Python中处理运行时异常的标准做法。当程序尝试访问一个不存在的目录时,会抛出
FileNotFoundError
;当没有足够的权限读取某个目录时,则会抛出
PermissionError
。通过捕获这些特定的异常,我们可以优雅地处理错误,而不是让程序直接崩溃。我个人倾向于捕获这些具体的错误类型,这样可以根据不同的错误给出更精确的反馈,而不是简单地捕获所有
Exception
。当然,最后捕获一个通用的
Exception
作为兜底也是个好习惯,以防出现一些未预料到的问题。
以上就是python中怎么列出目录下的所有文件?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1371188.html
微信扫一扫
支付宝扫一扫