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.walkreturnsfilesas just the filename (not the full path). If your code was accidentally checking therootdirectory's suffix instead of the file's, that would explain it. - Case sensitivity issues: On Linux/macOS,
.MDis 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
.mdwith 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.walkwill throw aFileNotFoundErrorif./pages/isn't there. - Permission errors: If you don't have access to a subdirectory inside
pages/, the script will crash with aPermissionError. - Empty directory or no .md files: The script will run but give no output, which might be confusing.
- Symbolic links: By default,
os.walkfollows symlinks—if you don't want that, addfollowlinks=Falseto theos.walkcall.
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
- Add the debug
elseprint statement to see exactly which files are being skipped—this will tell you if the issue is case sensitivity or something else. - Verify
./pages/actually exists (runls ./pages/in your terminal to check). - 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
相关产品推荐
相关产品推荐

