CSVWriter不保存数据到文件 - 为什么? [英] CSVWriter not saving data to file - WHY?

查看:505
本文介绍了CSVWriter不保存数据到文件 - 为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python新手有点沮丧的csv模块。在这个速度,如果我自己写文件解析器,但我想做的东西Pythonic的方法,这将是更容易....

Python newbie getting a bit frustrated with the csv module. At this rate, it would have been easier if I wrote the file parser myself, but I want to do things the Pythonic way ....

我写了一个小

这里是我的代码片段:

import csv

wrtr = csv.writer(open('myfile.csv','wb'),delimiter=',', quotechar='"')

for row in rows:
    wrtr.writerow([row.field1,row.field2,row.field3])

文件myfile.csv已成功创建,但它是空的 - 但是有一个锁,因为它仍然被Python进程使用。已写入内存中的文件,但尚未刷新到磁盘。

The file myfile.csv is created successfully, yet it is empty - but has a lock on it, as its still being used by the Python process. It seems that the data has been written to the file in memory, but it has not yet been flushed to disk.

由于Python进程持有该文件的锁,那么我假设下面是我的问题:

Since the Python process is holding a lock on the file, then I assume that I am responsible for releasing the lock. Here are my questions:


  1. 如何让python刷新到磁盘

  2. 如何关闭在csv.writer()方法中打开的文件?


推荐答案

使用

with open('myfile.csv','wb') as myfile:
    wrtr = csv.writer(myfile, delimiter=',', quotechar='"')
    for row in rows:
        wrtr.writerow([row.field1,row.field2,row.field3])
        myfile.flush() # whenever you want

myfile = open('myfile.csv','wb')
wrtr = csv.writer(myfile, delimiter=',', quotechar='"')
for row in rows:
    wrtr.writerow([row.field1,row.field2,row.field3])
    myfile.flush() # whenever you want, and/or
myfile.close() # when you're done.

第一种方法的好处是,您的文件也会自动正确关闭例外。

The nice thing about the first approach is that your file will also be automatically properly closed in case of an Exception.

如果您希望文件对象是匿名的,那么它只会在程序退出时关闭。何时或是否刷新取决于操作系统 - 因此它可能永远不会直到退出。

If you want your file object to be anonymous, then it will only be closed when the program exits. When or whether it is flushed depends on the OS - so it might be never until exit.

这篇关于CSVWriter不保存数据到文件 - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆