gpt4 book ai didi

python - csv writer没有关闭文件

转载 作者:IT老高 更新时间:2023-10-28 21:06:13 26 4
gpt4 key购买 nike

我正在读取一个 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 关闭文件。当我打开文件时,它以只读方式打开它,因为它说它仍然处于打开状态。

完成后如何关闭file_subset1.csv?

最佳答案

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)

关于python - csv writer没有关闭文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3347775/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com