Python 新手对 csv 模块感到有点沮丧。按照这个速度,如果我自己编写文件解析器会更容易,但我想以 Pythonic 方式做事......
我已经编写了一个小 python 脚本,应该将我的数据保存到 CSV 文件中。
以下是我的代码片段:
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 进程使用。看起来数据已经写入内存中的文件,但还没有刷新到磁盘。
由于Python进程持有文件的锁,所以我假设我负责释放锁。这是我的问题:
- 如何让 python 刷新到磁盘
- 如何关闭在 csv.writer() 方法中打开的文件?
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 ....
I have written a little python script that should save my data into a CSV file.
Here is a snippet of my code:
import csv
wrtr = csv.writer(open('myfile.csv','wb'),delimiter=',', quotechar='"')
for row in rows:
wrtr.writerow([row.field1,row.field2,row.field3])
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.
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:
- How do I get python to flush to disk
- How do I close the file that was opened in the csv.writer() method?
发布评论
评论(2)
使用
or
第一种方法的好处是,如果出现异常,您的文件也会自动正确关闭。
如果您希望文件对象是匿名的,那么它只会在程序退出时关闭。何时或是否刷新取决于操作系统 - 因此在退出之前可能永远不会刷新。
Use
or
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.
flush() 和
close()
方法rel="noreferrer">文件对象。或者使用with
。The
flush()
andclose()
methods of the file object. Or usewith
.