4

我试图创建一个脚本来打开一个文件并将每个“hola”替换为“hello”。

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

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

f.close()

但我收到这个错误:

Traceback(最近一次调用最后一次):
文件“prueba.py”,第 3 行,in for line in f: IOError: [Errno 9] Bad file descriptor

任何的想法?

哈维

4

4 回答 4

7
open('test.txt', 'w').write(open('test.txt', 'r').read().replace('hola', 'hello'))

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

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'))
于 2010-04-05T09:31:28.873 回答
4

您已打开文件进行写入,但您正在从中读取。打开原始文件进行读取,并打开一个新文件进行写入。替换后,重命名原来的out和新的in。

于 2010-04-05T09:27:35.517 回答
4

您的主要问题是您要先打开文件进行写入。当您打开一个文件进行写入时,该文件的内容被删除,这使得替换非常困难!如果你想替换文件中的单词,你有一个三步过程:

  1. 将文件读入字符串
  2. 在该字符串中进行替换
  3. 将该字符串写入文件

在代码中:

# open for reading first since we need to get the text out
f = open('kk.txt','r')
# step 1
data = f.read()
# step 2
data = data.replace("hola", "hello")
f.close()
# *now* open for writing
f = open('kk.txt', 'w')
# step 3
f.write(data)
f.close()
于 2010-04-05T09:38:39.420 回答
3

您还可以查看with语句。

于 2010-04-05T09:31:14.910 回答