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

如何遍历目录下的文本文件?排除.py文件或指定子目录方案咨询

Solution for Targeted File Traversal in Python

Got it, let's fix this for you! Your current code grabs every file in the directory—including your own script—which is definitely not what you want. Let's break down both of your desired scenarios with clean, safe code.

1. Traverse a Specific Subdirectory

If you want to read all files in a designated subdirectory (and avoid your script entirely), just point glob directly to that subdirectory path. This is super straightforward and keeps your script out of the target files.

Basic Subdirectory Traversal

import glob

# Replace "target_subdir" with your actual subdirectory name
for file_path in glob.glob('./target_subdir/*'):
    # Use `with` statement to auto-close files (safer than manual f.close())
    with open(file_path, 'r') as f:
        text = f.read()
        # Add your text processing logic here
        print(f"Successfully read: {file_path}")

Recursive Traversal (Include Sub-Subdirectories)

If you need to dig into nested subdirectories under your target folder, use the recursive=True flag:

import glob
import os

# The ** matches any level of subdirectories
for file_path in glob.glob('./target_subdir/**/*', recursive=True):
    # Make sure we're only reading files, not directories
    if os.path.isfile(file_path):
        with open(file_path, 'r') as f:
            text = f.read()
            print(f"Read nested file: {file_path}")

2. Only Traverse Text Files in the Current Directory

If you want to stay in the same directory as your script but skip non-text files (and your script itself), we can filter by file extensions or explicitly exclude your script.

Filter by Text File Extensions

Most text files have standard extensions like .txt, .md, .rst—target those directly:

import glob

# List of text file extensions you want to include
text_extensions = ['*.txt', '*.md', '*.rst', '*.csv']

for ext in text_extensions:
    for file_path in glob.glob(ext):
        with open(file_path, 'r') as f:
            text = f.read()
            print(f"Read text file: {file_path}")

Exclude Your Script (Just in Case)

If your script happens to share an extension with your text files (unlikely, but safe to handle), explicitly skip it using os.path.basename(__file__):

import glob
import os

# Get the name of your current script (e.g., "my_script.py")
current_script = os.path.basename(__file__)

for file_path in glob.glob('*.txt'):
    # Skip the script itself and only process files (not directories)
    if file_path != current_script and os.path.isfile(file_path):
        with open(file_path, 'r') as f:
            text = f.read()
            print(f"Read text file (skipped script): {file_path}")

Bonus: Check File Type (Beyond Extensions)

If you need to verify a file is actually text (not a binary file with a .txt extension), you can add a quick check to avoid decoding errors:

import glob
import os

def is_text_file(file_path):
    try:
        with open(file_path, 'r') as f:
            f.read(100)  # Read a small chunk to test encoding
        return True
    except UnicodeDecodeError:
        return False

for file_path in glob.glob('*'):
    if os.path.isfile(file_path) and file_path != os.path.basename(__file__) and is_text_file(file_path):
        with open(file_path, 'r') as f:
            text = f.read()
            print(f"Confirmed text file: {file_path}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:30:49