如何使用Pandas拆分文本文件数据并转换为指定格式CSV?
解决方案
这里提供两种实用的处理方式,帮你快速完成文本转目标CSV格式的需求:
方法一:Python脚本处理
适合需要灵活调整逻辑的场景,代码简洁易修改:
import csv current_day = "" output_rows = [] header_written = False with open("input.txt", "r") as infile: for line in infile: line = line.strip() if not line: continue # 识别Day标题行(排除含A/B/C的表头行) if "A" not in line and "B" not in line and "C" not in line: current_day = line elif line.startswith("A"): # 生成带Day列的总表头,只写一次 if not header_written: output_rows.append(line.split() + ["Day"]) header_written = True else: # 给数据行追加当前Day信息 output_rows.append(line.split() + [current_day]) # 写入目标文件 with open("output.csv", "w", newline="") as outfile: writer = csv.writer(outfile, delimiter=",") writer.writerows(output_rows)
使用说明:
- 将你的输入文本命名为
input.txt,和脚本放在同一目录 - 运行脚本后会生成标准逗号分隔的
output.csv;如果需要保留示例中的空格分隔,把代码里的delimiter=","改成delimiter=" "即可
方法二:Awk命令行处理
适合Linux/macOS环境下快速批量处理,无需写脚本文件:
BEGIN { print "A,B,C,Day" } /A B C/ { next } !/^[0-9]/ { current_day = $0; next } { print $1 "," $2 "," $3 "," current_day }
使用说明:
- 把输入文本命名为
input.txt,在终端执行命令:awk 'BEGIN {print "A,B,C,Day"} /A B C/ {next} !/^[0-9]/ {current_day=$0;next} {print $1","$2","$3","current_day}' input.txt > output.csv - 若要输出空格分隔的格式,把命令里的逗号替换成三个空格即可
内容的提问来源于stack exchange,提问作者Hue
相关产品推荐
相关产品推荐

