Replace a particular text from a CSV file without knowing the text
Question: I need to replace a particular value from a text file, without knowing the
value of the string to be replaced. All I know is the line number, and the
location of the value in that line which has to be replaced. This has to be
done using Python 2.7

for example, the file is like this:

    
    
    a,b,c,s,d,f
    s,d,f,g,d,f
    a,d,s,f,g,r
    a,s,d,f,e,c
    

My code goes like this:

    
    
    point_file = open(pointfile,'r+')
    read_lines = point_file.readlines()
    arr1 = []
    for i in range(len(read_lines)):
        arr1.append(read_lines[i])
    

Now I need to replace

    
    
    arr1[3].split(',')[3]
    

How to do that?

**Edit**

I do not wish to achieve this using a temporary copy file and then overwrite
the existing file. I need to edit the value **in place** the **existing**
file.


Answer: OK, so I'm assuming fields can have any value (or the following can be
shortened considerably by clever substitution tricks).

    
    
    from __future__ import print_function
    
    target = (3, 3) # Coordinates of the replaced value
    new_val = 'X'   # New value for the replaced cells
    with open('src.txt') as f_src:
        data = f_src.read().strip()
    
    table = [line.split(',') for line in data.split('\n')]
    old_val = table[target[0]][target[1]]
    new_data = '\n'.join(
                    ','.join(
                        new_val if cell == old_val else cell
                        for cell in row)
                    for row in table)
    
    with open('tgt.txt', 'w') as f_tgt:
        print(new_data, file=f_tgt)
    

My test `src.txt`:

    
    
    a,b,c,s,d,f
    s,d,f,g,d,f
    a,d,s,f,g,r
    a,s,d,f,e,c
    

My output `tgt.txt`:

    
    
    a,b,c,s,d,X
    s,d,X,g,d,X
    a,d,s,X,g,r
    a,s,d,X,e,c
    

