Python:替换.txt文件中的String

时间:2015-08-29 20:20:45

标签: python string python-3.x sys

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”文件。如果有 ADVERB VERB NOON ,请用户输入替换这些字符串。然后重写“panda.txt”文件。 我的错误代码是: pandaRead = pandaFile.read() io.UnsupportedOperation: not readable 我在Windows Vista Home版本上使用Sublime text 2和Python 3.4。

1 个答案:

答案 0 :(得分:2)

您的代码中存在多个错误。我将向您解释,但为了进一步开发,请始终保持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)