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

如何用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 with statements 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:

  1. Missing import csv: The csv module isn't available unless you explicitly import it.
  2. Incorrect csv.reader usage: By default, csv.reader expects commas, so it would treat each space-separated line as a single column instead of two.
  3. Incomplete return statement: Your function didn't return the collected time and pos lists.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:46:47