如何用Python将字段行式记录文本转换为纵向CSV文件
问题描述
现有一个文本文件,每个字段单独占一行,以特定头部标识新记录的开始。需要用Python将其转换为标准CSV格式,未适用的字段留空或设为0。
示例输入:
WERF this is vendor1 data this is col1 : 20 this is col2 : 30 here is col1 scenario2: 1 here is col2 scenario2: 3 ADEF this is vendor2 data this is col1 : 2 this is col2 : 3 TRGF this is vendor3 data this is col1 : 10 this is col2 : 12 PSDFAA this is vendor4 data this is col1 : 4 this is col2 : 7 here is col1 scenario2: 12 here is col2 scenario2: 11
预期输出(标准CSV格式):
Vendor,this is col1,this is col2,here is col1 scenario2,here is col2 scenario2 WERF,20,30,1,3 ADEF,2,3,, TRGF,10,12,, PSDFAA,4,7,12,11
Python实现方案
以下是直接可运行的代码,核心逻辑为先收集所有字段名,再逐条解析记录并补全缺失字段:
import csv def convert_to_csv(input_file, output_file): records = [] all_fields = {'Vendor'} # 固定包含Vendor字段 current_record = {} with open(input_file, 'r', encoding='utf-8') as f: for line in f: line = line.strip() if not line: continue # 跳过空行 # 识别新记录头部:行首为4位及以上大写字母标识 first_segment = line.split()[0] if first_segment.isupper() and len(first_segment) >= 4: # 保存上一条记录(如果存在) if current_record: records.append(current_record) # 初始化新记录 current_record = {'Vendor': first_segment} else: # 解析字段行:分割字段名与值 if ':' in line: field_part, value_part = line.split(':', 1) field_name = field_part.strip() value = value_part.strip() current_record[field_name] = value all_fields.add(field_name) # 处理最后一条未保存的记录 if current_record: records.append(current_record) # 对字段名排序,保证输出顺序稳定 sorted_fields = sorted(all_fields) # 写入CSV文件 with open(output_file, 'w', newline='', encoding='utf-8') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=sorted_fields) writer.writeheader() for record in records: # 缺失字段填充为空字符串,需设为0可替换成''为'0' filled_record = {field: record.get(field, '') for field in sorted_fields} writer.writerow(filled_record) # 调用示例:替换为你的输入输出文件路径 convert_to_csv('input.txt', 'output.csv')
关键说明
- 记录识别规则:代码通过行首是否为4位及以上大写字母判断新记录,若你的实际标识规则不同,修改
first_segment.isupper() and len(first_segment) >=4这一条件即可。 - 字段自动收集:遍历过程中自动收集所有出现过的字段,确保CSV表头包含全部可能字段。
- 缺失字段处理:默认用空字符串填充缺失字段,如需设为0,将代码中
''替换为'0'即可。 - 标准CSV输出:使用Python内置
csv模块的DictWriter,保证输出符合CSV规范,可直接用Excel等工具打开。
内容的提问来源于stack exchange,提问作者PythonDeveloper
相关产品推荐
相关产品推荐

