CSVWriter 在我写数据的那一刻没有将数据保存到文件中 [英] CSVWriter not saving data to file the moment I write it

查看:22
本文介绍了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天全站免登陆