如何基于CSV列表在目录中查找文件并移动至指定文件夹?(Python)
Fixing Your CSV-Driven File Mover Script
Hey there! Let's break down what's going wrong with your code and fix it up. I see a few key issues that are causing your script to jump straight to the else branch and stop after the first row:
Key Issues in Your Current Code
- Path Escaping Problems: Windows paths use backslashes (
\), which are treated as escape characters in Python strings. You need to use raw strings (prefix withr) or double backslashes to avoid this. - Incorrect File Existence Check:
if file_name in existing_path_prefixchecks if the filename is a substring of the path string, not if the actual file exists at that path. You should useos.path.exists()instead. - Unnecessary
breakStatement: This stops your loop after the first row, so you'll never process more than one file. - Skipping the Header Row: Your CSV has a header, but your script tries to process it as a data row (looking for a file named "File Name").
- Potential Encoding Issues: Excel-exported CSVs sometimes have a UTF-8 BOM, so specifying
encoding='utf-8-sig'can prevent read errors.
Fixed Version of Your Original Script
Here's the adjusted code that addresses all these issues:
import csv import os import shutil def main(): # Use raw strings for Windows paths to avoid escape character issues csv_file = r"G:\Key Accounts\Ebills\Lex Bot Test\Test 2\EB Mapping.csv" base_path = r"G:\Key Accounts\Ebills\Lex Bot Test\Test 2\PDFs" with open(csv_file, 'r', encoding='utf-8-sig') as f: reader = csv.reader(f) next(reader) # Skip the header row for row in reader: if not row: # Skip empty rows if any continue file_name = row[0].strip() folder_name = row[1].strip() existing_file_path = os.path.join(base_path, file_name) target_folder_path = os.path.join(base_path, folder_name) # Check if the file actually exists at the path if os.path.exists(existing_file_path): print(f"Found file: {existing_file_path}") # Ensure target folder exists (you said it does, but just in case) os.makedirs(target_folder_path, exist_ok=True) shutil.move(existing_file_path, os.path.join(target_folder_path, file_name)) print(f"Successfully moved to: {target_folder_path}") else: print(f"Warning: File not found - {existing_file_path}") if __name__ == "__main__": main()
Alternative: Using Pandas for Cleaner Handling
If you're open to using Pandas, it makes parsing the CSV even simpler and more readable:
import os import shutil import pandas as pd def main(): base_path = r"G:\Key Accounts\Ebills\Lex Bot Test\Test 2\PDFs" df = pd.read_csv(r"G:\Key Accounts\Ebills\Lex Bot Test\Test 2\EB Mapping.csv") for _, row in df.iterrows(): file_name = str(row['File Name']).strip() folder_name = str(row['Folder Name']).strip() existing_file_path = os.path.join(base_path, file_name) target_folder_path = os.path.join(base_path, folder_name) if os.path.exists(existing_file_path): os.makedirs(target_folder_path, exist_ok=True) shutil.move(existing_file_path, os.path.join(target_folder_path, file_name)) print(f"Moved: {file_name} -> {folder_name}") else: print(f"File missing: {file_name}") if __name__ == "__main__": main()
Notes for Both Solutions
- The
exist_ok=Trueinos.makedirs()is a safety net in case any target folders are missing (you mentioned they exist, but this prevents crashes if something's off). - Adding
.strip()to filenames/folder names removes any accidental leading/trailing spaces that might cause mismatches. - Raw strings (
r"path") eliminate escape character headaches in Windows paths.
内容的提问来源于stack exchange,提问作者Lex Dunko
相关产品推荐
相关产品推荐

