【问题标题】:csv.writer.writerows missing rows from listcsv.writer.writerows 列表中缺少行
【发布时间】:2017-04-16 18:05:24
【问题描述】:

我是 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 文件中,它会起作用(它被添加了,但是两次......)。

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 写入参数。

另一条信息:

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

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

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

感谢您的帮助!

【问题讨论】:

  • 不要隐藏像list这样的内置函数:更改你的变量名。
  • 你的列表是空的,你怎么得到19112行?发布你的真实代码……
  • 嗨洛朗。你的意思是我应该将我的列表重命名为其他名称吗?我没有包括构建列表的代码部分(它正在打开其他 csv 并将它们合并在一起)。我不确定您提供的链接是否适用于我的问题,但感谢您的帮助!

标签: python csv


【解决方案1】:

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

这里是修复:

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 离开 with-suite 时为您提供该文件。有了 with,你会 永远不要忽略再次关闭文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 2016-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多