如何给文本文件中每行字符串添加双引号及逗号并输出到新文件
这里有几种实用的方法可以实现你的需求:
方法1:Python脚本(跨平台通用)
写一个简单的Python脚本,能处理任意大小的文本文件,还能正确处理最后一行不加逗号的情况:
# 输入文件路径 input_file = "input.txt" # 输出文件路径 output_file = "output.txt" with open(input_file, 'r', encoding='utf-8') as f_in, open(output_file, 'w', encoding='utf-8') as f_out: # 读取所有行,去除每行的换行符和空白内容 lines = [line.strip() for line in f_in if line.strip()] total_lines = len(lines) for idx, word in enumerate(lines): if idx < total_lines - 1: # 非最后一行,添加引号和逗号 f_out.write(f'"{word}",\n') else: # 最后一行,只加引号 f_out.write(f'"{word}"\n')
使用说明:把代码保存为process_words.py,将你的输入文件命名为input.txt放在同一目录,运行python process_words.py即可生成处理后的output.txt。
方法2:Shell sed命令(Linux/macOS)
如果用Linux或macOS终端,一行命令就能搞定,无需编写脚本:
sed -e 's/^/"/' -e 's/$/",/' input.txt | sed '$s/,$//' > output.txt
逻辑解释:
- 第一个
sed命令:给每行开头添加",结尾添加", - 第二个
sed命令:移除最后一行末尾的逗号 - 最终结果直接写入
output.txt
方法3:Shell awk命令(Linux/macOS)
awk的处理逻辑更直观,同样一行命令完成:
awk 'NR==1{prev=$0;next} {print "\""prev"\","; prev=$0} END{print "\""prev"\""}' input.txt > output.txt
逻辑解释:
- 先缓存第一行内容,后续每一行输出上一行的处理结果(加引号和逗号)
- 最后单独处理最后一行,只添加引号不加分号
内容的提问来源于stack exchange,提问作者Satyam Shishodiya
相关产品推荐
相关产品推荐

