1
tiedosto = input("Anna luettavan tiedoston nimi: ") #Here i take user added "File"
sana = input("Sana joka korvataan: ") #Here is word that i want to replace
korvaa = input("Sana jolla korvataan: ") #Here is word that i want to replace
td = open(tiedosto,"r+")#here we open the file
for line in td: 
    muutos = td.read().replace(sana, korvaa) #Here it replaces the words

    td.write(muutos)#Doesent work?
    print(muutos)
td.close()

So the td.write(muutos) why doesent it save to the file?

Larezz
  • 11
  • 2

1 Answers1

0

td is of the type file. you want to convert it to a list of lines.
What you should do is:
for line in td.readlines()

Also for replacing words, try using fileinput.

from this post:
fileinput already supports inplace editing. It redirects stdout to the file in this case:

#!/usr/bin/env python3
import fileinput

with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(text_to_search, replacement_text), end='')
Daniel
  • 95
  • 8