Python批量转换TXT到CSV脚本问题排查:仅生成单列CSV及文件名后缀异常
Hey there! Let's tackle the two issues you're running into with your Python script—getting single-column CSVs and those annoying .txt.csv filenames. Here's what's going wrong and how to fix it:
1. Why Your CSV Only Has One Column
Looking at your pd.read_csv line, you set delimiter = ',', but your column names are all suffixed with \t (tab characters). That tells me your original TXT files are tab-separated, not comma-separated. Pandas is trying to split on commas, but since there aren't any, it shoves everything into one column.
Fix:
Change the delimiter to '\t' and clean up those extra \t characters in your column names (they'll make your CSV headers messy otherwise):
df = pd.read_csv(txt_file, delimiter='\t', names=['Messpunkt', 'Zeichnungspunkt', 'Eigenschaft', 'Position', 'Sollmaß', 'Toleranz', 'Abweichung', 'Lage'])
2. Why You're Getting .txt.csv Filenames
Right now, you're taking the full original filename (like file.txt) and appending .csv to it, which gives you file.txt.csv. You need to strip the .txt extension first before adding .csv.
Fix:
Use os.path.splitext() to get the filename without its extension, and use os.path.join() for safer path handling (it works across Windows/macOS/Linux):
# Get the filename without .txt extension base_filename = os.path.splitext(txt_file)[0] # Save with clean .csv extension df.to_csv(os.path.join(output_dir, f"{base_filename}.csv"), index=False)
Full Modified Script
Here's the complete fixed code, with an extra check to skip non-TXT files (prevents errors if your input folder has other file types):
import os import pandas as pd input_dir = "C:\\path where original data is" output_dir = "C:\\path for csv files" os.chdir(input_dir) txt_files = os.listdir('.') print(txt_files) for txt_file in txt_files: # Skip any files that aren't .txt if not txt_file.endswith('.txt'): continue # Read tab-separated TXT file correctly df = pd.read_csv(txt_file, delimiter='\t', names=['Messpunkt', 'Zeichnungspunkt', 'Eigenschaft', 'Position', 'Sollmaß', 'Toleranz', 'Abweichung', 'Lage']) # Generate clean output filename and save base_filename = os.path.splitext(txt_file)[0] df.to_csv(os.path.join(output_dir, f"{base_filename}.csv"), index=False)
内容的提问来源于stack exchange,提问作者joho

