如何用Python将空格分隔的TXT文件转换为CSV文件
Convert Space-Separated TXT to CSV Using Python
Got it, let's fix this and get your space-separated TXT converted to CSV smoothly. Here's how to do it properly in Python:
Solution Code (Memory-Efficient Approach)
import csv def txt_to_csv(input_filename, output_filename): # Open input TXT and output CSV files (auto-closes when done) with open(input_filename, 'r') as txt_file, open(output_filename, 'w', newline='') as csv_file: csv_writer = csv.writer(csv_file) # Process header line: split space-separated header into CSV columns header = txt_file.readline().strip().split() csv_writer.writerow(header) # Process each data line for line in txt_file: # Split line by spaces (handles multiple spaces if present) data_values = line.strip().split() csv_writer.writerow(data_values) # Example usage: replace with your file names txt_to_csv('input_data.txt', 'output_data.csv')
Explanation
- Import
csv: This built-in module handles CSV formatting correctly, including proper line endings and column separation. - File Handling: Using
withstatements ensures files are closed automatically, avoiding resource leaks. - Header Conversion: The first line (header) is split from "time pos" into a list
['time', 'pos'], then written as the CSV header. - Data Rows: Each line is stripped of extra whitespace, split into individual values, and written as a comma-separated row in the CSV.
Fixes for Your Initial Code
Your original code had a few gaps:
- Missing
import csv: Thecsvmodule isn't available unless you explicitly import it. - Incorrect
csv.readerusage: By default,csv.readerexpects commas, so it would treat each space-separated line as a single column instead of two. - Incomplete
returnstatement: Your function didn't return the collectedtimeandposlists.
Alternative: Using Lists (Closer to Your Original Idea)
If you prefer storing data in lists first, here's a revised version:
import csv def get_data(filename): time = [] pos = [] with open(filename, 'r') as txtfile: next(txtfile) # Skip header line for line in txtfile: t, p = line.strip().split() # Split each line into two values time.append(t) pos.append(p) return time, pos def write_csv(time_list, pos_list, output_filename): with open(output_filename, 'w', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(['time', 'pos']) # Pair time and pos values and write each row for t, p in zip(time_list, pos_list): writer.writerow([t, p]) # Example usage times, positions = get_data('input_data.txt') write_csv(times, positions, 'output_data.csv')
Either approach works—use the first one for large datasets (it doesn't store all data in memory at once) or the second if you need to manipulate the data before writing to CSV.
内容的提问来源于stack exchange,提问作者TheTechGuy
相关产品推荐
相关产品推荐

