簡體   English   中英

列表未正確寫入CSV文件

[英]List not writing into a CSV file properly

我有一個類似的list

('so glad', 'happy')
('it is so sad', 'sad')

我想將此列表寫入CSV文件,例如:

column1          column2
so glad          happy
it is so sad     sad

我用下面的代碼來做到這一點:

with open('test.csv', "a") as outfile:
    for entries in my_list:
        outfile.write(entries)
        outfile.write("\n")

但是它以以下方式寫入CSV文件

column1
so glad
happy
it is so sad
sad

如何使此代碼按預期執行?

import csv

with open('test.csv', 'wb') as outfile:
    wr = csv.writer(outfile, quoting=csv.QUOTE_ALL)
    wr.writerow(entries)

對於python 3:使用writerow寫入從列表中提取的行(可迭代)

import csv
my_list =[('so glad', 'happy'),
('it is so sad', 'sad')]
with open('mycsv.csv','w+') as fileobj:
    csvwriter = csv.writer(fileobj)
    for row in my_list:
        csvwriter.writerow(row)

或使用需要迭代的writerows (可迭代是可用於迭代的任何事物,因此my_list是可迭代的列表)並獲取行並相應地保存它們

import csv
my_list =[('so so glad', 'happy'),
('it is so sad', 'sad')]
with open('mycsv.csv','w+') as fileobj:
    csvwriter = csv.writer(fileobj)
    csvwriter.writerows(my_list)

對於python 2:

with open('mycsv.csv','w+') as fileobj:

用wb代替w +

mycsv.csv的輸出為:

so so glad,happy
it is so sad,sad

還要注意,我在這里使用w +作為模式,該模式會截斷,如果已存在則清空csv文件或創建一個新文件並向其中寫入內容

有多種寫模式供您使用。 看看python的文件模式文檔

在Windows上,附加到模式的'b'以二進制模式打開文件,因此也有'rb','wb'和'r + b'之類的模式。 Windows上的Python區分文本文件和二進制文件。 當讀取或寫入數據時,文本文件中的行尾字符會自動更改。 對於ASCII文本文件,對文件數據進行這種幕后修改是可以的,但它會破壞JPEG或EXE文件中的二進制數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM