csv writer not closing file

后端 未结 5 1179
小蘑菇
小蘑菇 2020-12-05 23:36

im reading a csv file and then writing a new one:

import csv

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

import collections
count         


        
5条回答
  •  一整个雨季
    2020-12-06 00:31

    close the file, not the csv writer. To do this, you'll need to open the file first before instantiating your writer rather than keeping it all in one line.

    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()
    

    Also, I would suggest keeping your imports at the top of the script and closing the first file when you're done with it.

提交回复
热议问题