【问题标题】:How to add quotes in the file如何在文件中添加引号
【发布时间】: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 标签在这里合适吗?

标签: python regex shell


【解决方案1】:

假设您有一个文件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"

【讨论】:

    【解决方案2】:

    我已更新我的答案以涵盖其他包含空格的文本情况。

    看到你的问题中有一个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 "
    猜你喜欢
    • 2017-11-21
    • 2013-06-14
    • 1970-01-01
    • 2015-08-10
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    相关资源
    最近更新 更多