csv.writer.writerowslis中缺少行

2024-09-29 17:19:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手。在

我有一个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文件中,就可以工作了(添加了两次……)。在

^{pr2}$

如果我试图单独添加列表结尾,它似乎不起作用。我在想可能是csv写入参数出错了。在

另一条信息:

如果我打开文件添加“newline='',那么它会向其中写入更多的行(尽管不是全部)

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

我打开或写入csv的方式(或者用方言?)一定有一个简单的错误在

谢谢你的帮助!在


Tags: 文件csv信息元素列表newline原因open
1条回答
网友
1楼 · 发布于 2024-09-29 17:19:36

我找到了答案!我没有在脚本结束之前关闭文件句柄,这会留下未写入的行。在

解决方法如下:

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

Close the filehandle before the script ends. Closing the filehandle will also flush any strings waiting to be written. If you don't flush and the script ends, some output may never get written.

Using the with open(...) as f syntax is useful because it will close the file for you when Python leaves the with-suite. With with, you'll never omit closing a file again.

相关问题 更多 >

    热门问题