CSVWriter在我写入数据时未将数据保存到文件中 [英] CSVWriter not saving data to file the moment I write it

查看:466
本文介绍了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 ....

我写了一个小python脚本,应该将我的数据保存到CSV文件中.

I have written a little python script that should save my data into a CSV file.

这是我的代码段:

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天全站免登陆