Overwriting a specific row in a csv file using Python's CSV module

前端 未结 2 1125
甜味超标
甜味超标 2020-12-10 18:02

I\'m using Python\'s csv module to do some reading and writing of csv files.

I\'ve got the reading fine and appending to the csv fine, but I want to be able to over

相关标签:
2条回答
  • 2020-12-10 18:13

    I will add to Steven Answer :

    import csv
    
    bottle_list = []
    
    # Read all data from the csv file.
    with open('a.csv', 'rb') as b:
        bottles = csv.reader(b)
        bottle_list.extend(bottles)
    
    # data to override in the format {line_num_to_override:data_to_write}. 
    line_to_override = {1:['e', 'c', 'd'] }
    
    # Write data to the csv file and replace the lines in the line_to_override dict.
    with open('a.csv', 'wb') as b:
        writer = csv.writer(b)
        for line, row in enumerate(bottle_list):
             data = line_to_override.get(line, row)
             writer.writerow(data)
    
    0 讨论(0)
  • 2020-12-10 18:38

    You cannot overwrite a single row in the CSV file. You'll have to write all the rows you want to a new file and then rename it back to the original file name.

    Your pattern of usage may fit a database better than a CSV file. Look into the sqlite3 module for a lightweight database.

    0 讨论(0)
提交回复
热议问题