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

如何使用Python将含表格结构的.txt文件转换为.csv文件

将带表格结构的TXT文件转为CSV(Python实现)

从你提供的文件内容来看,这是固定宽度格式的表格(部分字段包含空格,无法用简单的空格/制表符分割),下面提供两种Python实现方案:

方案一:用pandas快速处理(推荐)

pandas能自动识别固定宽度的列结构,处理带空格的字段更可靠:

1. 安装pandas

如果还没安装,执行命令:

pip install pandas

2. 转换代码

创建Python脚本(比如convert.py):

import pandas as pd

# 读取固定宽度的TXT文件,自动识别列边界
df = pd.read_fwf('你的输入文件.txt')

# 保存为CSV,index=False表示不生成行索引
df.to_csv('输出文件.csv', index=False, encoding='utf-8')

注意:

  • 替换你的输入文件.txt和输出文件.csv为实际的文件路径
  • 如果自动识别列宽不准确,可以手动指定各列宽度(需要对照你的文件调整数值):
# 示例列宽,根据你的表头和数据实际长度修改
col_widths = [19, 14, 25, 25, 35, 30, 25, 14, 20, 20, 20, 100, 20, 3, 8, 6, 10, 8, 20, 30, 30, 20, 20, 20, 2, 10, 2, 20, 25, 25, 25, 30, 20, 20, 20]
df = pd.read_fwf('你的输入文件.txt', widths=col_widths)

3. 运行脚本

在终端执行:

python convert.py

方案二:用Python内置csv模块(无需第三方库)

如果不想安装pandas,可手动处理,但仅适合字段格式规则的场景:

import csv

# 手动定义列的分割位置(根据你的文件调整)
column_positions = [0, 19, 33, 58, 83, 118, 148, 173, 187, 207, 227, 247, 347, 367, 370, 378, 384, 394, 402, 422, 452, 482, 502, 522, 542, 544, 554, 556, 576, 601, 626, 651, 681, 701, 721, 741]

with open('你的输入文件.txt', 'r', encoding='utf-8') as txt_file, open('输出文件.csv', 'w', newline='', encoding='utf-8') as csv_file:
    writer = csv.writer(csv_file)
    for line in txt_file:
        # 根据指定位置分割每行内容
        row = [line[start:end].strip() for start, end in zip(column_positions[:-1], column_positions[1:])]
        writer.writerow(row)

内容的提问来源于stack exchange,提问作者user19016544

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 20:36:23