为了账号安全,请及时绑定邮箱和手机立即绑定

Python CSV - 双双引号被写入 CSV 文件?

Python CSV - 双双引号被写入 CSV 文件?

HUX布斯 2021-11-02 15:26:52
我正在尝试将一些数据写入 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"",Album2,""Balls to the Wall"",Album3,""Restless and Wild"",Album4,""Let There Be Rock"",Album5,""Big Ones"",Album6,""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",Album2,"Balls to the Wall",Album3,"Restless and Wild",Album4,"Let There Be Rock",Album5,"Big Ones",Album6,"Jagged Little Pill",Album...但我得到了这个:1,""For Those About To Rock We Salute You"",Album2,""Balls to the Wall"",Album3,""Restless and Wild"",Album4,""Let There Be Rock"",Album5,""Big Ones"",Album6,""Jagged Little Pill"",Album...
查看完整描述

1 回答

?
胡说叔叔

TA贡献1804条经验 获得超8个赞

这是获取结果的演示:


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


查看完整回答
反对 回复 2021-11-02
  • 1 回答
  • 0 关注
  • 311 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号