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

如何读取目录下所有.txt文件?现有代码仅读取单个文件的问题求助

解决仅读取单个文本文件的问题

Hey there! Let's break down why your code is only pulling content from one text file, and fix it up.

问题根源

Your current code uses os.listdir(path) which returns every single item in the directory—including subfolders, images, or other non-text files. If the loop hits something that isn't a readable text file, Python will throw an error and stop the loop entirely, leaving you with only the first successful file read.

Also, a quick note: you don't need f.close() when using a with statement—it automatically handles closing the file once the block finishes!

解决方案1:优化原有代码

We'll add checks to filter only .txt files and make sure we're not trying to read directories. Here's the updated code:

import os

path = "你的目录路径"  # 替换成你的实际路径
for filename in os.listdir(path):
    # 过滤出.txt文件,同时确认是文件而非目录
    if filename.endswith('.txt') and os.path.isfile(os.path.join(path, filename)):
        filepath = os.path.join(path, filename)
        # 建议指定编码,避免跨系统的乱码问题
        with open(filepath, mode='r', encoding='utf-8') as f:
            content = f.read()
            thelist = content.splitlines()
            print(filepath)
            print(content)
            print()

解决方案2:用Pathlib更优雅地实现(Python 3.4+推荐)

Pathlib makes file path handling cleaner and more intuitive. This version automatically finds all .txt files without extra checks:

from pathlib import Path

path = Path("你的目录路径")
# 用glob遍历当前目录下的所有.txt文件;如果要递归子目录,改用rglob('*.txt')
for txt_file in path.glob('*.txt'):
    with open(txt_file, 'r', encoding='utf-8') as f:
        content = f.read()
        print(txt_file)
        print(content)
        print()

StackOverflow相关参考思路

On StackOverflow, you'll find tons of similar discussions by searching terms like "Python os.listdir only reads one file" or "Python iterate over text files in directory". Common topics covered include:

  • Filtering specific file types in a directory
  • Properly constructing file paths to avoid errors
  • Best practices for using with statements for file handling
  • Fixing encoding issues when reading text files

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:19:08