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

为何按扩展名复制文件的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 extension variable is a list of all file extensions in the directory, so checking if extension == 'json' will never evaluate to true. You need to check each file's extension one by one.
  • Missing shutil import: The copyfile function isn't part of the os module—you need to import the shutil module 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 json or csv subfolders 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 shutil to 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.join to build full file paths (more reliable than hardcoding, especially across different OSes).
  • Added .lower() to handle case-insensitive extensions (so .JSON or .CSV files get sorted correctly too).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 10:53:14