【问题标题】:Python newbie: trying to create a script that opens a file and replaces wordsPython新手:尝试创建一个打开文件并替换单词的脚本
【发布时间】:2010-04-05 09:25:10
【问题描述】:

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

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

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

f.close()

但是我得到了这个错误:

回溯(最近一次通话最后一次):
文件“prueba.py”,第 3 行,在 对于 f 中的行:IOError:[Errno 9] 错误的文件描述符

有什么想法吗?

贾维

【问题讨论】:

  • 为什么用“w”模式打开文件?你用什么教程来学习 Python?

标签: python file-manipulation


【解决方案1】:
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'))

【讨论】:

  • 没错,但是对于初学者来说,这是最简单直接的方法。
  • Answer shadows 'input' 内置,也许 src_text 可能是一个更好的变量名?
  • @Paul:也可以。已编辑。
【解决方案2】:

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

  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()

【讨论】:

  • 我们应该从一开始就教初学者使用 'with' - 请参阅 Max Shawabkeh 的回答。
  • @paul 我不反对;然而,由于用户已经对操作文件的概念有困难,我最初决定让我的答案尽可能接近他的原始代码。由于用户随后提出的问题指出 Python 2.5(需要从 __future__ 进行特殊导入),所以我想我最好不要更改它。当然,如果不那么明确,另一个答案同样正确。
  • 请注意,简单的替换将 a) 不匹配 "Hola" 并给出 "Hello",并且 b) 匹配 'scholar' 中的 'hola' 给出 'schellor' .
【解决方案3】:

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

【讨论】:

    【解决方案4】:

    您还可以查看with 声明。

    【讨论】:

      猜你喜欢
      • 2011-03-04
      • 1970-01-01
      • 2015-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 1970-01-01
      • 2018-11-23
      相关资源
      最近更新 更多