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

Python递归文件搜索求助:无法正确筛选./pages/下的.md文件

Hey there! Let's troubleshoot why your os.walk code isn't catching those .md files (and fix that stubborn else branch), plus cover the edge cases you mentioned.

First: Why your if statement is always hitting the else branch

The most common culprits here are usually simple oversights:

  • You're checking the wrong thing: Remember, os.walk returns files as just the filename (not the full path). If your code was accidentally checking the root directory's suffix instead of the file's, that would explain it.
  • Case sensitivity issues: On Linux/macOS, .MD is different from .md—if your files have uppercase extensions, a straight .endswith('.md') will miss them.
  • Typos: Double-check you didn't write something like .md with a space, or mix up the extension syntax.

Fix the core file-finding logic

Here's a corrected snippet that addresses these issues:

import os

target_dir = "./pages/"
for root, dirs, files in os.walk(target_dir):
    for file in files:
        # Handle both .md and .MD extensions
        if file.lower().endswith('.md'):
            # Get the full path to the file (useful for later operations)
            full_file_path = os.path.join(root, file)
            print(f"Found Markdown file: {full_file_path}")
        # Optional: Uncomment to debug what's being skipped
        # else:
        #     print(f"Skipping non-MD file: {file}")

Now, let's cover those unhandled exceptions

Your mention of "unexpressed exceptions" makes sense—there are several edge cases that can break your script if not handled:

  • Target directory doesn't exist: os.walk will throw a FileNotFoundError if ./pages/ isn't there.
  • Permission errors: If you don't have access to a subdirectory inside pages/, the script will crash with a PermissionError.
  • Empty directory or no .md files: The script will run but give no output, which might be confusing.
  • Symbolic links: By default, os.walk follows symlinks—if you don't want that, add followlinks=False to the os.walk call.

Improved code with error handling

This version covers all those scenarios:

import os

target_dir = "./pages/"

try:
    md_files = []
    # Disable symlink following to avoid unintended directory traversal
    for root, dirs, files in os.walk(target_dir, followlinks=False):
        for file in files:
            if file.lower().endswith('.md'):
                md_files.append(os.path.join(root, file))
    
    if not md_files:
        print("Oops—no Markdown files found in ./pages/.")
    else:
        print(f"Success! Found {len(md_files)} Markdown files:")
        for path in md_files:
            print(f"- {path}")

except FileNotFoundError:
    print(f"Error: The directory '{target_dir}' doesn't exist. Double-check the path!")
except PermissionError:
    print(f"Error: You don't have permission to access some folders in '{target_dir}'.")
except Exception as e:
    print(f"Unexpected error popped up: {str(e)}")

Quick troubleshooting steps

  1. Add the debug else print statement to see exactly which files are being skipped—this will tell you if the issue is case sensitivity or something else.
  2. Verify ./pages/ actually exists (run ls ./pages/ in your terminal to check).
  3. Make sure you're running the script from the correct working directory—if you're in a subfolder, ./pages/ might point to the wrong place.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:47:03