简体   繁体   English

csv.writerow 似乎无法写入行

[英]csv.writerow appears to be failing to write rows

I have a script that writes close to 800,000 rows to various CSV files.我有一个脚本,可以将近 800,000 行写入各种 CSV 文件。

for col in data:
        with open('output/{}.csv'.format(col), mode, encoding='utf-8', newline='') as f:
            writer = csv.writer(f, lineterminator = '\n')
            if mode == 'w':
                writer.writerow(headers)
            for row in data[col]:
                writer.writerow(row)

On modern machines this appears to function correctly and write all rows.在现代机器上,这似乎是正确的 function 并写入所有行。

However on older machines (Using mechanical hard drives) there is around 35% to 40% rows missing in total.然而,在较旧的机器(使用机械硬盘)上,总共丢失了大约 35% 到 40% 的行。

Here is a list of the machine, and the total rows written (out of 815143):这是机器的列表,以及写入的总行数(共 815143 行):

  • Macbook pro osx 10.15(16gb ram, SSD) - 815143 Macbook pro osx 10.15(16gb 内存,SSD)- 815143
  • Windows 10 (32gb ram, NVme) - 815143 Windows 10(32gb 内存,NVme)- 815143
  • Windows 10 (4gb ram, HDD) - 543737 Windows 10(4GB 内存,硬盘)- 543737
  • Windows 10 (4gb ram, HDD) - 501335 Windows 10(4GB 内存,硬盘)- 501335

Is there something I am doing incorrectly that is causing this?是不是我做错了什么导致了这种情况?

Or are write failures something to consider?或者写入失败需要考虑吗? when using csv.write ?使用csv.write时?

It appears that the cause of this issue is Python's output buffer.看来此问题的原因是 Python 的 output 缓冲区。

https://blog.finxter.com/what-is-python-output-buffering-and-how-to-disable-it/ https://blog.finxter.com/what-is-python-output-buffering-and-how-to-disable-it/

passing the -u flag when running python appears to fix the issue of csv rows not being written on slower machines.在运行 python 时传递-u标志似乎可以解决 csv 行未在较慢的机器上写入的问题。

Eg:例如:

python -u file.py argument

Hopefully this helps anybody else who encounters the same issue.希望这可以帮助遇到同样问题的其他人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM