You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用os模块访问文件夹,如何通过os.listdir()遍历获取指定文件

os.listdir() 入参说明及遍历实现方案

os.listdir() 的括号内仅需要填写你要遍历的目标文件夹路径即可,支持两种路径格式:

  • 相对路径:相对于当前Python运行时工作目录的路径,比如要遍历当前目录下的res子文件夹,写os.listdir('./res')即可;如果参数留空,默认遍历当前工作目录。
  • 绝对路径:从系统根目录开始的完整路径,Windows下示例为os.listdir('D:/work/project/files'),macOS/Linux下示例为os.listdir('/home/user/work/project/files')。

注意:os.listdir() 仅返回目标目录下的文件/子文件夹名称,不会返回完整路径,如果你需要访问具体文件,需要手动拼接路径,推荐使用os.path.join()方法避免不同系统的路径分隔符兼容问题。

完整遍历访问文件示例

import os

# 你要访问的目标文件夹路径
target_folder = "./your_target_folder"

for item_name in os.listdir(target_folder):
    # 拼接得到文件/子文件夹的完整路径
    full_path = os.path.join(target_folder, item_name)
    # 判断是普通文件再执行访问操作
    if os.path.isfile(full_path):
        # 这里可以写你的文件访问逻辑,比如读取、修改等
        print(f"可访问文件:{full_path}")

如果需要固定遍历Python脚本本身所在的目录,不需要手动写路径,可以用以下写法:

import os
# __file__ 是当前脚本的完整路径,os.path.dirname取它的上级目录即脚本所在文件夹
script_dir = os.path.dirname(os.path.abspath(__file__))
for item_name in os.listdir(script_dir):
    print(item_name)

内容的提问来源于stack exchange,提问作者cgnseahawk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 20:27:04