为何按扩展名复制文件的Python代码无法运行?附相关代码
Fixing Your File Classification & Copy Script
Got it, let's get your file sorting code working properly. Your current script has a few key issues that are keeping it from running as expected—here's how to fix them:
Key Issues in Your Original Code
- You're comparing a list to a string: The
extensionvariable is a list of all file extensions in the directory, so checkingif extension == 'json'will never evaluate to true. You need to check each file's extension one by one. - Missing
shutilimport: Thecopyfilefunction isn't part of theosmodule—you need to import theshutilmodule to use it. - Incorrect path usage for
copyfile: This function requires full paths to the source file and destination file (not just the parent folders). - Unchecked target folders: If the
jsonorcsvsubfolders don't exist yet, the copy operation will throw an error.
Corrected Code
import os import shutil # Define base and target paths base_dir = r"C:\Users\user\Desktop\common" json_dir = os.path.join(base_dir, "json") csv_dir = os.path.join(base_dir, "csv") # Create target folders if they don't exist (no error if they already exist) os.makedirs(json_dir, exist_ok=True) os.makedirs(csv_dir, exist_ok=True) # Iterate over files in the top-level common folder for _, _, filenames in os.walk(base_dir): for filename in filenames: # Get full path to the source file source_path = os.path.join(base_dir, filename) # Extract file extension (lowercase to handle .JSON/.CSV cases) file_extension = filename.split(".")[-1].lower() # Copy to the correct subfolder if file_extension == "json": dest_path = os.path.join(json_dir, filename) shutil.copyfile(source_path, dest_path) elif file_extension == "csv": dest_path = os.path.join(csv_dir, filename) shutil.copyfile(source_path, dest_path) break # Stop after processing the top-level directory
What Changed?
- Added
import shutilto access the file copy function. - Used
os.makedirs(..., exist_ok=True)to safely create the target subfolders without errors if they already exist. - Loop through each file individually instead of collecting all extensions first.
- Used
os.path.jointo build full file paths (more reliable than hardcoding, especially across different OSes). - Added
.lower()to handle case-insensitive extensions (so.JSONor.CSVfiles get sorted correctly too).
内容的提问来源于stack exchange,提问作者aysh
相关产品推荐
相关产品推荐

