咨询单/批量转换特定结构文本文件为CSV的技术方法
单个文本文件转CSV的实现方法
你的文本文件结构是首行标题、次行列名、后续为空格分隔的数据,转CSV可以用以下两种方式实现:
Python 脚本方式
适合跨平台使用,逻辑清晰易修改:
# 单个文件转换示例 input_file = "sample.txt" output_file = "sample.csv" with open(input_file, 'r', encoding='utf-8') as f: lines = f.readlines() # 跳过首行标题,处理列名(将多空格分隔转为逗号) csv_header = ','.join(lines[1].strip().split()) # 处理数据行,过滤空行并转换格式 csv_content = [csv_header] for line in lines[2:]: stripped_line = line.strip() if stripped_line: csv_content.append(','.join(stripped_line.split())) # 写入CSV文件 with open(output_file, 'w', encoding='utf-8', newline='') as f: f.write('\n'.join(csv_content))
命令行(awk)方式
适合Linux/macOS或有Git Bash的Windows用户,快速无依赖:
# 跳过首行标题,将所有行的多空格替换为逗号后输出到CSV awk 'NR==1{next} {gsub(/ +/, ","); print}' sample.txt > sample.csv
批量处理100个文件的高效方案
批量处理的核心是遍历目标文件,重复执行单个文件的转换逻辑,以下是两种高效实现:
Python 批量脚本
可灵活控制文件路径、过滤规则,适合大规模处理:
import os # 配置输入输出文件夹路径 input_folder = "./raw_texts" output_folder = "./converted_csvs" # 确保输出文件夹存在 os.makedirs(output_folder, exist_ok=True) # 遍历所有txt文件 for filename in os.listdir(input_folder): if not filename.endswith(".txt"): continue input_path = os.path.join(input_folder, filename) output_filename = os.path.splitext(filename)[0] + ".csv" output_path = os.path.join(output_folder, output_filename) # 读取并处理文件 with open(input_path, 'r', encoding='utf-8') as f: lines = f.readlines() csv_header = ','.join(lines[1].strip().split()) csv_content = [csv_header] for line in lines[2:]: stripped_line = line.strip() if stripped_line: csv_content.append(','.join(stripped_line.split())) # 写入CSV with open(output_path, 'w', encoding='utf-8', newline='') as f: f.write('\n'.join(csv_content)) print("所有文件转换完成")
Shell 批量命令
适合熟悉命令行的用户,无需编写脚本:
# 遍历当前目录下所有txt文件,批量转换为CSV for file in *.txt; do awk 'NR==1{next} {gsub(/ +/, ","); print}' "$file" > "${file%.txt}.csv" done
内容的提问来源于stack exchange,提问作者Mod_x
相关产品推荐
相关产品推荐

