0

Hey I'm working on this project where I take this text and translate it and store it back into the same CSV file. The next open column is at index 10 or Column K. I've been trying to write the data but I just can't get it.

Reading works fine. I tried to do all this into single while loop but I couldn't get it to work. Sorry for any formatting errors!

from googletrans import Translator
import csv

translater = Translator()
f = open("@ElNuevoDia.csv", "r+")
csv_f = csv.reader(f)
csv_wf = csv.writer(f)
tmp = {}
x = 0

for row in csv_f:
    tmp[x] = translater.translate(row[4], dest="en")
    #print(tmp[x].text)
    #print("\n")
    #print(tmp[x].text)
    x = x + 1
x = 0
f.close()
csv_wf = csv.writer(f)

for row in csv_wf:
        csv_wf[10].writerow(tmp[x].text)
f.close()
ellivron
  • 19
  • 2

1 Answers1

0

You should update row in reader and then write it back (as you mentioned in the comment, writer is not iterable). Something like that (part of your code):

for row in csv_f:
    row[10] = translater.translate(row[4], dest="en")
    tmp[x] = row
    x = x + 1
x = 0
f.close()
csv_wf = csv.writer(f)

for row in tmp:
        csv_wf.writerow(row)
f.close()

Edit 1:

For text variable you can do that:

row[10] = translater.translate(row[4], dest="en").text

and you can write it back in one step:

csv_wf.writerows(tmp)
Nerxis
  • 3,452
  • 2
  • 23
  • 39
  • I just need the .text variable from the tmp list and it doesn't look like this will do that, it'll include all the things. Also, what does updating the row mean? And how would I include a header variable. Is that the append function? – ellivron Jan 30 '18 at 15:56
  • Check for example [this link](https://stackoverflow.com/questions/11033590/change-specific-value-in-csv-file-via-python) - you have to read all lines, modify what you want (just use .text variable you're mentioning) and then write all lines back, – Nerxis Jan 30 '18 at 16:17