unable to write to CSV after replace
<p>I have an input file, in which I am making an string replace operation.</p>

<p>I read the file cell by cell, replace the string and then write it back to a new CSV file.</p>

<pre><code>input_file = open('/Users/tcssig/Desktop/unstacked2.csv', 'r', encoding='utf-8')
output_file = open('/Users/tcssig/Desktop/unstacked3.csv', 'w', encoding='utf-8')
writer = csv.writer(output_file , delimiter=' ')
reader = csv.reader(input_file)
for row in reader:
    for string in row:
       data = [string.replace('read','write')]
       print(data)
       writer.writerow(data)
</code></pre>

<p>Above code runs well, but I get an empty output file.</p>

<pre><code>Example of data :

    reading reading reading reading
interval        0   1   2   3

who axis


Mikael  X   0   10  20  30

Mikael  Y   50  40  30  20

Mikael  Z   100 90  80  70

Mike    X   0   0.1 0.2 0.3

Mike    Y   0.5 0.4 0.3 0.2
</code></pre>

<p>Mike    Z   1   0.9 0.8 0.7</p>

<p>What am i missing?</p>

<p>Content of input file:</p>

<pre><code>"Roll No" English read Science
"Roll No" English Write Science
</code></pre>

<p><strong>Problem with your code:</strong></p>

<ol>
<li>As mentioned by <strong>@Scott</strong>, files are not closed.</li>
<li><p>Your are reading cell by <code>for string in row:</code> and replacing string there. But after replacement you are writing that cell as row in your file. For example, output file with your code looks file :</p>

<p>Roll No</p>

<p>English</p>

<p>read</p>

<p>Science</p></li>
</ol>

<p>This is due to above mentioned reason i.e. you are writing each cell.</p>

<p><strong>How to make it working?</strong></p>

<p><em>Comments inline with code</em></p>

<pre><code>import csv
input_file = open('mark.csv', 'r', encoding='utf-8')
output_file = open('result.csv', 'w')
writer = csv.writer(output_file , delimiter=' ', encoding='utf-8')
reader = csv.reader(input_file)
for row in reader:
    #Initailize empty list for each row
    data = []
    for string in row:
       #Replace and add to data list
       data.append(string.replace('read','write'))
    #Now write complete
    writer.writerow(data)

input_file.close()
output_file.close()
</code></pre>

<p><strong>Output:</strong></p>

<pre><code>"Roll No" English write Science

"Roll No" English Write Science
</code></pre>

<p>You can achieve same thing without <code>csv</code> module.</p>

<pre><code>with open("mark.csv") as input_file:
    with open("result.csv",'w') as output_file:
        for line in input_file:
            new_line = (line.replace("read","write")).replace(","," ")
            output_file.write(new_line)
</code></pre>

python csv