【问题标题】:Python: Replace String in a .txt filePython:替换 .txt 文件中的字符串
【发布时间】:2015-11-24 06:03:45
【问题描述】:
import os, sys
pandaFile = open("panda.txt", "w")
pandaRead = pandaFile.read()

if "NOON" in pandaRead:
    print("Enter a noon:")
    noon = input()
    str.replace("NOON",noon)

if "ADJECTIVE" in pandaRead:
    print("Enter an adjective:")
    adjective = input()
    str.replace("ADJECTIVE", adjective)

if "VERB" in pandaRead:
    print("Enter and verb:")
    verb = input()
    str.replace("VERB",verb)

newcontent = open("panda.txt","w")

我的目标是打开文件“Panda.txt”文件。如果有ADVERBVERBNOON,用用户输入替换这些字符串。并重写“panda.txt”文件. 我的错误代码是: pandaRead = pandaFile.read() io.UnsupportedOperation: not readable 我在 Windows Vista Home 版本上使用带有 Python 3.4 的 Sublime text 2。

【问题讨论】:

  • 那么您的实际问题是什么?
  • 你的代码哪里出错了?
  • 我建议你应该做一些关于文件输入输出和正则表达式的教程
  • 它不起作用。我有一条错误消息 pandaRead = pandaFile.read() io.UnsupportedOperation: not readable。谢谢
  • 将第 2 行替换为:pandaFile = open("panda.txt", "r") 以读取模式打开文件而不是写入

标签: python string python-3.x sys


【解决方案1】:

您的代码中有几个错误。我会向你解释它们,但为了进一步发展,请始终保留Python reference website 以查看你调用的方法的用法。

以下是我必须从您的代码中处理的各种错误:

考虑到这些,以下代码示例是(我假设)您打算执行的操作:

import os , sys

# With is a special bloc statement,
# closing your variable pandaFile at the end of the bloc.
with open("panda.txt", "r") as pandaFile:
    pandaRead = pandaFile.read()

if "NOON" in pandaRead:
    noon = input("Enter a noon:")
    pandaRead = pandaRead.replace("NOON", noon) 

if "ADJECTIVE" in pandaRead:
    adjective = input("Enter an adjective:")
    pandaRead = pandaRead.replace("ADJECTIVE", adjective)

if "VERB" in pandaRead:
    verb = input("Enter and verb:")
    pandaRead = pandaRead.replace("VERB",verb)

with open("panda.txt", "w") as pandaFile:
    pandaFile.write(pandaRead)

【讨论】:

  • 谢谢安托万。干净的代码!现在我收到错误消息 adjective = input("Enter an adjective:") EOFError: EOF when reading a line 。我在想也许是因为我使用的是 Sublime 文本。而且它实际上不允许 input()。但是中午的第一个输入有效。
  • 抱歉,我无法重现您的错误,不过我正在使用 linux。您如何运行脚本以及尝试输入什么内容?
  • 没关系。不过非常感谢。我从命令行运行脚本。我有超过 1 个 NOON ,也许这就是原因?
  • 我猜这是 sublime text 的命令行,因为您的问题与此非常相似:stackoverflow.com/questions/12547683/…
猜你喜欢
  • 1970-01-01
  • 2018-08-29
  • 1970-01-01
  • 1970-01-01
  • 2015-07-06
  • 1970-01-01
  • 2020-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多