【发布时间】:2020-05-13 08:37:34
【问题描述】:
下面有文件
123,PEN BOOK
124,BALL
125,BOOK
126,PENCIL BOOK
我需要加引号
期待
"123","PEN BOOK"
"124","BALL"
"125","BOOK"
"126","PENCIL BOOK"
【问题讨论】:
-
shell标签在这里合适吗?
下面有文件
123,PEN BOOK
124,BALL
125,BOOK
126,PENCIL BOOK
我需要加引号
期待
"123","PEN BOOK"
"124","BALL"
"125","BOOK"
"126","PENCIL BOOK"
【问题讨论】:
shell 标签在这里合适吗?
假设您有一个文件test.txt,其内容如下:
123,PEN
124,BALL
125,BOOK
126,PENCIL
您可以使用如下代码创建一个临时文件,其中包含带引号的内容并替换原始文件:
import os
with open("test.txt") as i: # open file for reading, i = input file
with open("temp.txt", "w") as o: # open temp file in write mode, o = output
for l in i: # read each line
o.write('"{}","{}"\n'.format(l.split(',')[0],l.split(',')[1].split('\n')[0]))
os.remove('test.txt') # remove the old file
os.rename('temp.txt','test.txt') # resave the temp file as the new file
输出:
"123","PEN"
"124","BALL"
"125","BOOK"
"126","PENCIL"
【讨论】:
我已更新我的答案以涵盖其他包含空格的文本情况。
看到你的问题中有一个regex 标签,你可以使用这样的东西:
import re
text = """123,PEN
124,BALL
125,BOOK
126,PENCIL
123,PEN BOOK"""
new_text = re.sub(r'(\d+),([\w\s]+)$', r'"\1","\2"', text, flags=re.M)
【讨论】:
awk -F',' '{printf "\"%s\",\"%s\"\n", $1,$2}' <your-file>
123,PEN BOOK 预期结果是"123,PEN BOOK "