【问题标题】:Writing to csv split text because of double quotes由于双引号而写入csv拆分文本
【发布时间】:2021-04-16 01:34:02
【问题描述】:

我正在尝试将列表写入 csv,但是当字符串中有双引号时,它会将文本拆分到另一个单元格。有没有办法在不删除双引号的情况下将其保留在一个单元格中?

我的清单

alst = [['John', 'Smith', 'Google, and Samsung'],['John', 'Smith', '"Google", and "Samsung"'],['John', 'Smith', 'Google ", and Samsung']]

output = open('output.csv', 'w')
output.write('first, last, desc\n')
for item in alst:
    output.write('"{0}","{1}","{2}"\n'.format(item[0], item[1], item[2]))
output.close()

在excel中输出文件

first | last  | desc                  | (Blank) 
John  | Smith | Google, and Samsung   
John  | Smith | Google"               |  and "Samsung""
John  | Smith | Google                |  and Samsung"

我想要得到什么

first | last  | desc                 
John  | Smith | Google, and Samsung   
John  | Smith | "Google", and "Samsung" 
John  | Smith | Google ", and Samsung              

字符串中只有一个双引号,它以逗号分隔。我该如何防止这种情况?我需要处理列表吗?我仍然想在列表中保留双引号。

【问题讨论】:

    标签: python csv


    【解决方案1】:

    改用csv.writer() 并将您的列表传递给作者。

    with open('output.csv', 'w', newline='') as output:
        writer = csv.writer(output)
        writer.writerow(['First', 'Last', 'Desc'])
        writer.writerows(alst)
    

    【讨论】:

    • 有什么办法可以在不使用 csv 包的情况下解决这个问题?
    • 很可能是的。然而,csv 库是内置的,专门为此而构建。有什么理由不想使用它?
    • 我正在尝试做一个没有导入功能的项目,但由于某种原因我无法正确输出这部分。
    • @Hal 除非项目有限制在没有导入的情况下执行此操作,老实说,只需使用 csv。您在文本条目中遇到逗号问题,因此您需要找到一种方法来忽略它或定义不同的分隔符,然后让 CSV 文件接受该分隔符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 2022-08-06
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 2015-11-25
    相关资源
    最近更新 更多