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()
所以td.write(muutos)为什么要将它保存到文件中?
答案 0 :(得分:0)
td是类型文件。你想把它转换成一个行列表
你应该做的是:
for line in td.readlines()
另外,对于替换单词,请尝试使用fileinput。
来自this post:
fileinput
已经支持就地编辑。在这种情况下,它会将stdout
重定向到文件:
#!/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='')