Antonio Banderas
Antonio Banderas

Reputation: 31

OverWrite an existing list in CSV files Python

I have a csv files with player attributes:

['Peter Regin', '2', 'DAN', 'N', '1987', '6', '6', '199', '74', '2', '608000', '', '77', '52', '74', '72', '58', '72', '71', '72', '70', '72', '74', '68', '74', '41', '40', '51']
['Andrej Sekera', '8', 'SVK', 'N', '1987', '6', '6', '198', '72', '3', '1323000', '', '65', '39', '89', '78', '75', '70', '72', '56', '53', '56', '57', '72', '57', '59', '70', '51']

For example, I want to check if a player is a CENTER ('2' in position 1 in my list) and after I want to modify the 12 element (which is '77' for Peter Regin)

How can I do that using the CSV module ?

import csv


class ManipulationFichier:


    def __init__(self, fichier):
        self.fichier = fichier

    def read(self):

        with open(self.fichier) as f:
            reader = csv.reader(f)

            for row  in reader:
                print(row)


    def write(self):

        with open(self.fichier) as f:
            writer = csv.writer(f)

            for row in f:
                if row[1] == 2: 
                    writer.writerows(row[1] for row in f)

Which do nothing important..

Thanks,

Upvotes: 1

Views: 1446

Answers (1)

9000
9000

Reputation: 40904

In general, CSV files cannot be reliably modified in-place.

Read the entire file into memory (usually a list of lists, as in your example), modify the data, then write the entire file back.

Unless your file is really huge, and you do this really often, the performance hit will be negligible.

Upvotes: 2

Related Questions