1

Good day,

I tried to change a word in a certain column,using index, in a csv file ,but it is not changed.

My code that I tried to use:

import csv

with open('INPUT.CSV', 'r') as file1, open('OUTPUT.csv','w',newline='') as file2:
   reader = csv.reader(file1, delimiter=',')
   writer = csv.writer(outfile, delimiter=',')

   for row in reader:
        row[0].replace('word','changed word')# I want to replace in first column=row[0] 'word' with 'changed word'
        writer.writerow(row)

The output file is same with the input, no changed.

Can someboby help me in this way?Many thanks in advance!

Sorin Beginner
  • 91
  • 1
  • 4
  • 8

2 Answers2

0

A working example would be better (output is open as file2 but writer is given outfile)

But in any case your problem is replace

  • replace returns a copy of the string (with replaced text if the criteria matches)

But you are discarding the returned value. You are actually changing nothing in row[0]

Solution:

replaced = row[0].replace('word','changed word')  # I want to replace in first column=row[0] 'word' with 'changed word'
row[0] = replaced
writer.writerow(row)
mementum
  • 3,153
  • 13
  • 20
  • Thank you @mementum for your solution...I tried the code with it but it seems that the change is not done only in the specific row (row[x]), it replace all matches that were found...Could be done something in this way? – Sorin Beginner Mar 23 '16 at 13:00
0

row[0].replace() does not replace anything in row[0]. From the docstring:

S.replace(old, new[, count]) -> string

Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

If you want to change the value of row[0] you need something like row[0] = new_value.

Stop harming Monica
  • 12,141
  • 1
  • 36
  • 56