【问题标题】:Python CSV - Double-double quotes being written into CSV file?Python CSV - 双双引号被写入 CSV 文件?
【发布时间】:2019-02-08 02:02:44
【问题描述】:

我正在尝试将一些数据写入 csv 文件。我只希望中间列在 csv 文件中有引号。我从保存在数组中的数据开始。以下是一些打印出来的条目:

['1', '"For Those About To Rock We Salute You"', 'Album']
['2', '"Balls to the Wall"', 'Album']
['3', '"Restless and Wild"', 'Album']
['4', '"Let There Be Rock"', 'Album']
['5', '"Big Ones"', 'Album']
['6', '"Jagged Little Pill"', 'Album']
...

如您所见,只有中间一列有引号。但是,当我将其写入 csv 文件时,这就是我得到的:

1,""For Those About To Rock We Salute You"",Album
2,""Balls to the Wall"",Album
3,""Restless and Wild"",Album
4,""Let There Be Rock"",Album
5,""Big Ones"",Album
6,""Jagged Little Pill"",Album
...

除了中间那一栏,一切都很好!我有双双引号!

我有一个函数可以获取数据(保存在数组数组中),并将其写入 csv 文件。我查看了QUOTE_NONE 方法,但这似乎不起作用...

file_data = ...
def write_node_csv():
    with open("./csv_files/albums.csv", mode='w') as csv_file:
        writer = csv.writer(csv_file, delimiter=',', quoting=csv.QUOTE_NONE, escapechar="\"")
        for data in file_data:
            writer.writerow(data)
    csv_file.close()

所以基本上我期待这个:

1,"For Those About To Rock We Salute You",Album
2,"Balls to the Wall",Album
3,"Restless and Wild",Album
4,"Let There Be Rock",Album
5,"Big Ones",Album
6,"Jagged Little Pill",Album
...

但我明白了:

1,""For Those About To Rock We Salute You"",Album
2,""Balls to the Wall"",Album
3,""Restless and Wild"",Album
4,""Let There Be Rock"",Album
5,""Big Ones"",Album
6,""Jagged Little Pill"",Album
...

【问题讨论】:

  • writer 中尝试quotechar=''(你不应该需要escapechar
  • @AChampion 它仍然给出相同的结果...
  • 我不能重复你的问题......我将在下面发布我的测试代码。你能发布你的原始数据(csv)吗?

标签: python csv


【解决方案1】:

这是获取结果的演示:

In []:
data = """'1', '"For Those About To Rock We Salute You"', 'Album'
'2', '"Balls to the Wall"', 'Album'
'3', '"Restless and Wild"', 'Album'
'4', '"Let There Be Rock"', 'Album'
'5', '"Big Ones"', 'Album'
'6', '"Jagged Little Pill"', 'Album'"""

import csv
with StringIO(data) as fin:
    reader = csv.reader(fin, quotechar="'", skipinitialspace=True)
    for row in reader:
        print(row)

Out[]:
['1', '"For Those About To Rock We Salute You"', 'Album']
['2', '"Balls to the Wall"', 'Album']
['3', '"Restless and Wild"', 'Album']
['4', '"Let There Be Rock"', 'Album']
['5', '"Big Ones"', 'Album']
['6', '"Jagged Little Pill"', 'Album']

In []:
with StringIO(data) as fin, StringIO() as fout:
    reader = csv.reader(fin, quotechar="'", skipinitialspace=True)
    writer = csv.writer(fout, quotechar='', quoting=csv.QUOTE_NONE)
    writer.writerows(reader)
    contents = fout.getvalue()
print(contents)

Out[]:
1,"For Those About To Rock We Salute You",Album
2,"Balls to the Wall",Album
3,"Restless and Wild",Album
4,"Let There Be Rock",Album
5,"Big Ones",Album
6,"Jagged Little Pill",Album

【讨论】:

  • 通过指定quotechar 而不是escapechar 它工作得很好!谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-11-02
  • 1970-01-01
  • 1970-01-01
  • 2014-04-22
  • 2019-10-07
  • 2017-09-28
  • 1970-01-01
  • 2014-05-05
相关资源
最近更新 更多