如何从DataFrame将大TXT转CSV?列合并异常求助
Hey there, let's get to the bottom of why your data is squishing into a single column instead of the 18650 columns you expect!
The Root Cause
Looking at your actual output, you can see values are separated by \t (tab characters), but in your code you told pandas to use ; as the delimiter. Since pandas couldn't find any semicolons in your txt file, it treated every entire row as a single column.
The Fix
Update your read_csv call to use the correct delimiter—tab characters (\t). You can use either sep='\t' or delimiter='\t' (they’re interchangeable in pandas). Also, your file path has a small redundancy: when using os.path.join, if the second argument is an absolute path, it overrides the first one, so we can clean that up too.
Here's the corrected code:
import os import pandas as pd save_path = "/Users/Desktop/Python-testing" # Use the direct absolute path for your input file (or fix the join if needed) in_filename = "/Users/Desktop/Python-testing/data_gene_sample_report.txt" out_filename = os.path.join(save_path, 'Output.csv') # Use tab as the separator to split columns correctly df = pd.read_csv(in_filename, sep='\t') df.to_csv(out_filename, index=False)
Bonus Tips
- If you’re ever unsure about the delimiter in your file, try
sep='\s+'to match any whitespace (tabs or spaces), or usepd.read_table()which defaults to tab-separated data. - Double-check your input file’s structure by opening it in a text editor to confirm the separator type—this will save you time debugging!
内容的提问来源于stack exchange,提问作者user10108293

