2016-12-01 83 views
-1

我是python的新手。csv.writer.writerows從列表中缺少的行

我有一個19188行的列表,我想保存爲csv。

當我將列表的行寫入csv時,它沒有最後一行(它停在19112處)。

你有什麼想法可能會導致這種情況?

這裏是我寫的CSV:

mycsvfile = open('file.csv', 'w') 
thedatawriter = csv.writer(mycsvfile, lineterminator = '\n') 
list = [] 
#list creation code 
thedatawriter.writerows(list) 

表的每一行有4個字符串元素。

另一條信息:

如果我創建一個包含只失蹤,把它們添加到CSV文件中的最後一個元素的列表,它種工作(它被添加,但兩次... ...) 。

mycsvfile = open('file.csv', 'w') 
thedatawriter = csv.writer(mycsvfile, lineterminator = '\n') 
list = [] 
#list creation code 
thedatawriter.writerows(list) 
list_end = [] 
#list_end creation code 
thedatawriter.writerows(list_end) 

如果我嘗試單獨添加list_end,它似乎並沒有工作。我在想可能有一個csv寫入參數,我錯了。

另一條信息:

如果我打開文件中添加「新行=‘’」,然後把它寫更多的行吧(雖然不是全部)

mycsvfile = open('file.csv', 'w', newline='') 

必須有一個在打開或寫入csv(或在方言中)的方式中發生簡單的錯誤

感謝您的幫助!

+0

不要像'list'這樣的函數建立陰影:改變你的變量名稱。 –

+0

您的列表爲空,您如何獲得19112行?發佈您的真實代碼... –

+0

[使用Python 2.7讀取和寫入CSV文件(包括unicode)]的可能重複(http://stackoverflow.com/questions/17245415/read-and-write-csv-files-including-unicode-with- python-2-7) –

回答

0

我找到了我的答案!在腳本結束之前,我沒有關閉文件句柄,這留下了未寫入的行。

這裏是修復:

with open('file.csv', 'w', newline='') as mycsvfile: 
    thedatawriter = csv.writer(mycsvfile, lineterminator = '\n') 
    thedatawriter.writerows(list) 

參見:Writing to CSV from list, write.row seems to stop in a strange place

關閉文件句柄的腳本之前結束。關閉文件句柄 也會刷新等待寫入的任何字符串。如果您不刷新 並且腳本結束,則某些輸出可能永遠不會寫入。

使用with open(...)as f語法很有用,因爲Python在離開套件時會爲您關閉 文件。隨着,你會 再也不會忽略關閉文件。