read and write on same csv file

前端 未结 5 1169
隐瞒了意图╮
隐瞒了意图╮ 2020-11-30 11:00

I am trying to read and write on the same CSV file:

file1 = open(file.csv, \'rb\')
file2 = open(file.csv, \'wb\')
read         


        
5条回答
  •  星月不相逢
    2020-11-30 11:26

    You can't open a file in both read and write modes at once.

    Your code could be modified as follows:-

    # Do the reading
    file1 = open(file.csv, 'rb')
    reader = csv.reader(file1)
    new_rows_list = []
    for row in reader:
       if row[2] == 'Test':
          new_row = [row[0], row[1], 'Somevalue']
          new_rows_list.append(new_row)
    file1.close()   # <---IMPORTANT
    
    # Do the writing
    file2 = open(file.csv, 'wb')
    writer = csv.writer(file2)
    writer.writerows(new_rows_list)
    file2.close()
    

    As Jason points out, if your CSV is too big for your memory, then you'll need to write to a different filename and then rename it. This will likely be a bit slower.

提交回复
热议问题