Python新手:尝试创建一个打开文件并替换单词的脚本

zii*_*web 4 python file-manipulation

我试图创建一个打开文件的脚本,并用'hello'替换每个'hola'.

f=open("kk.txt","w")

for line in f:
  if "hola" in line:
      line=line.replace('hola','hello')

f.close()
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:

回溯(最近一次调用最后一次):
文件"prueba.py",第3行,输入f中的行:IOError:[Errno 9]错误的文件描述符

任何的想法?

哈维

Max*_*keh 7

open('test.txt', 'w').write(open('test.txt', 'r').read().replace('hola', 'hello'))
Run Code Online (Sandbox Code Playgroud)

或者,如果要正确关闭文件:

with open('test.txt', 'r') as src:
    src_text = src.read()

with open('test.txt', 'w') as dst:
    dst.write(src_text.replace('hola', 'hello'))
Run Code Online (Sandbox Code Playgroud)