代码之家  ›  专栏  ›  技术社区  ›  AlexT

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

  •  2
  • AlexT  · 技术社区  · 7 年前

    我正在尝试将一些数据写入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
    ...
    

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

    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、“为即将摇滚的人们致敬”,专辑
    3、“不安与狂野”,专辑
    4、“让摇滚乐来吧”,专辑
    5、“大人物”专辑
    ...
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   AChampion    7 年前

    下面是获得结果的演示:

    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