csv writer不关闭文件

omhiaaxx  于 2023-05-11  发布在  其他
关注(0)|答案(6)|浏览(181)

我正在阅读一个csv文件,然后写一个新的:

import csv

with open('thefile.csv', 'rb') as f:
  data = list(csv.reader(f))

import collections
counter = collections.defaultdict(int)
for row in data:
    counter[row[11]] += 1

writer = csv.writer(open('/pythonwork/thefile_subset1.csv', 'w'))
for row in data:
    if counter[row[11]] >= 500:
       writer.writerow(row)

由于某种原因我不能得到csv.writer关闭文件.当我打开文件时,它将其打开为只读,因为它说仍然打开。
我如何关闭thefile_subset1.csv后,我做了吗?

wfsdck30

wfsdck301#

with open('/pythonwork/thefile_subset1.csv', 'w') as outfile:
    writer = csv.writer(outfile)
    for row in data:
        if counter[row[11]] >= 500:
           writer.writerow(row)
yptwkmov

yptwkmov2#

您可以将open命令拆分到它自己的变量中,以便以后可以关闭它。

f = open('/pythonwork/thefile_subset1.csv', 'w')
writer = csv.writer(f)
f.close()

csv.writer在尝试写入已关闭的文件时抛出ValueError

7rfyedvj

7rfyedvj3#

关闭文件,而不是csv writer。为此,您需要在示例化编写器之前首先打开文件,而不是将其全部保存在一行中。

import csv
import collections

with open('thefile.csv', 'rb') as f:
    data = list(csv.reader(f))

counter = collections.defaultdict(int)
for row in data:
    counter[row[11]] += 1

f.close()  # good idea to close if you're done with it

fSubset = open('/pythonwork/thefile_subset1.csv', 'w')
writer = csv.writer(fSubset)
for row in data:
    if counter[row[11]] >= 500:
        writer.writerow(row)

fSubset.close()

另外,我建议将导入放在脚本的顶部,并在完成后关闭第一个文件。

6mw9ycah

6mw9ycah4#

强制编写器清理:

del writer
xu3bshqb

xu3bshqb5#

尽管flush()可能会降低应用程序的性能,但它也是解决此问题的一种方法。

with open("path/to/file.csv", "w", newline="") as csvFile:
    # ... do your things ...
    # ... write to the CSV file ...
       
    csvFile.flush()

您可以在编写循环结束时调用它,也可以在每次调用编写器的writerow(..)方法之后调用它。在我的情况下,我不断地写入CSV文件,除非程序被终止,这是唯一可行的解决方案。
顺便说一句,如果你想知道是什么导致了这种情况,你最好看看你的操作系统的文件缓存方法。这实际上是由一种缓冲机制引起的,该机制是为了增强计算机的文件I/O性能而实现的。

fykwrbwg

fykwrbwg6#

看看区别:

with open('thefile.csv', 'rb') as f:
    data = list(csv.reader(f))

对比:

writer = csv.writer(open('/pythonwork/thefile_subset1.csv', 'w'))

相关问题