1

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,

1
  • Can you show us the code you have so far? Commented May 13, 2013 at 23:59

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What is the most effective way. So I should use the mmap module ? Or write in a list ? using the reader and append ?
Forget efficiency until you attain correct functioning. Do the simplest thing possible. I bet the bottlenecks of your program are going to be elsewhere :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.