How to overwrite a specific cell in a column (for example, column 5 and line 6) in a CSV file? The documentation for the CSV module did not find such an example.

    4 answers 4

    def update_csv_cell(address, new_value): filepath = '/home/idle/so/some.csv' dialect_params = dict(delimiter=';') col_num, row_num = address with open(filepath, 'r+b') as csvfile: reader = csv.reader(csvfile, **dialect_params) lines = [] for current_line in reader: if reader.line_num == row_num: current_line[col_num-1] = new_value lines.append(current_line) csvfile.seek(0) csv.writer(csvfile, **dialect_params).writerows(lines) csvfile.truncate() update_csv_cell(address=(5, 6), new_value='replaced') 

    The above is the base code, without error handling.

    Bad news more than good.

    Good: the csv module allows you to work with ordinary file objects, which means you have access to all methods of such objects (see seek, tell, etc.)

    Bad 1: the csv module reads the entire file, so during the iteration over the file lines, the tell method will always return the end position of the file, so there is no other simple solution than to read all the data, change it and save it on the horizon.

    Bad 2: The approach to accessing the file data by position in the document is unreliable, because if everything can be relatively stable with columns, then it is very possible not to guess with a number, thus spoiling the data.

      When working with CSV (and indeed when working with data) it is very convenient and almost always more productive to use Pandas :

      Example:

      read / parse CSV in Pandas Data Frame with the read_csv () method:

       import pandas as pd In [115]: df = pd.read_csv('c:/temp/example.csv', sep=',') In [116]: df Out[116]: ABCDE 0 54 9 74 73 59 1 34 20 66 81 14 2 89 33 87 98 41 3 74 78 19 4 25 4 30 12 7 52 29 5 33 45 39 73 81 6 49 28 48 69 99 

      change the 6th row and 5th column (note: in Pandas, as in Python, the numbering starts from zero):

       In [119]: df.ix[6-1, 5-1] += 1000 In [120]: df Out[120]: ABCDE 0 54 9 74 73 59 1 34 20 66 81 14 2 89 33 87 98 41 3 74 78 19 4 25 4 30 12 7 52 29 5 33 45 39 73 1081 6 49 28 48 69 99 

      write back to CSV:

       df.to_csv('c:/temp/example.csv', index=False) 

      Result:

       A,B,C,D,E 54,9,74,73,59 34,20,66,81,14 89,33,87,98,41 74,78,19,4,25 30,12,7,52,29 33,45,39,73,1081 49,28,48,69,99 

      How to quickly and easily generate test data (this is how test CSV was created):

       import numpy as np df = pd.DataFrame(np.random.randint(0,100,size=(7, 5)), columns=list('ABCDE')) df.to_csv('c:/temp/example.csv', index=False) 

      or in one line:

       pd.DataFrame(np.random.randint(0,100,size=(7, 5)), columns=list('ABCDE')).to_csv('c:/temp/example.csv', index=False) 
        • read file to list
        • change item in list
        • write list to file.

          Try without a module. If you can:

          • Read from file;
          • Break a string with a separator;
          • Write to file

          then you can solve your problem without using CSV.

          • with open (.... as f
          • str.split (here is your delimiter)
          • f.write (...
          • But split is wrong to use. The separator can be inside a string value enclosed in quotes. Like the line feed, by the way. - Qwertiy
          • I agree about the fact that it is not quite right. But if a person decides on his knee, even if not quite right. He will no longer need further advice! - sys_dev
          • I do not agree. No good, if it is somewhere quietly to work incorrectly. - Qwertiy
          • Getting knowledge is an iterative process. It is not possible to learn something without trying! The process of trying this means making mistakes. Man learns from mistakes! You can spend hours reading the theory and looking for a super-duper the right way. And it is possible to fix the code 5-6 times by writing the code “on the knee”, but to get specific knowledge how to and how not to! I offered to write at least somehow. Solve the problem even in some form! - sys_dev
          • one
            The fact is that this is not the same thing when a person does wrong himself and when he is intentionally advised to do wrong. And even without adding any reservations like "in most cases fit" or "If the file does not contain ..., then." A concrete solution is proposed. And for such a question that the result will not be visible and check, and if no one will change each file correctly. That is, an error will be detected when an armful of files is overwritten incorrectly. Perhaps overwritten irrevocably. Good situation? - Qwertiy