Pandas读取文件报FileNotFoundError[WinError3],路径正确仍异常
Let's break down why you're hitting that FileNotFoundError: [WinError 3] issue, even though you swear the path is correct.
The problem lies in how you're referencing subfolders in your loops. When you run os.listdir(path), it returns just the names of the folders inside C:/PanelComplete/FileForPeter/ (like 20180101), not their full absolute paths. Then when you call os.listdir(folder) next, Python looks for 20180101 in your current working directory—not inside C:/PanelComplete/FileForPeter/—which is why it can't find it.
Here's the corrected version of your code, with proper path handling and extra robustness checks:
import os import pandas as pd # Define your base input path base_path = 'C:/PanelComplete/FileForPeter/' # Make sure spath1 is properly defined (replace with your actual output directory) spath1 = 'C:/Your/Target/Output/Path/' # Iterate through each item in the base directory for folder_name in os.listdir(base_path): # Build the full path to the subfolder full_folder_path = os.path.join(base_path, folder_name) # Skip any items that aren't actual folders (prevents errors from loose files) if not os.path.isdir(full_folder_path): continue # Now loop through files inside the valid subfolder for file_name in os.listdir(full_folder_path): full_file_path = os.path.join(full_folder_path, file_name) # Only process CSV files to avoid non-CSV read errors if file_name.endswith('.csv'): df = pd.read_csv(full_file_path, engine='python') df1 = df.groupby('codprg').size().reset_index(name='counts') # Build the full output path safely output_file = os.path.join(spath1, f"{folder_name}.csv") df1.to_csv(output_file, index=False, encoding='utf-8')
Key fixes explained:
- Used
os.path.join()to safely construct full paths instead of manual string concatenation (this avoids missing slashes or OS-specific path separator issues). - Added
os.path.isdir()check to skip non-folder items in the base directory (prevents crashes if there are loose files there). - Added a
.csvfile extension check to avoid trying to read non-CSV files. - Clarified that
spath1needs a valid, defined output path (your original code references it but doesn't show its definition—don't forget to update that to your actual target folder).
This should resolve the FileNotFoundError and make your script more reliable overall.
内容的提问来源于stack exchange,提问作者Peter

