簡體   English   中英

Python:替換 .txt 文件中的字符串

[英]Python: Replace String in a .txt file

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。

您的代碼中有幾個錯誤。 我會向您解釋它們,但為了進一步開發,請始終保留Python 參考網站,以查看您調用的方法的用法。

以下是我必須從您的代碼中處理的各種錯誤:

考慮到這些,以下代碼示例是(我假設)您打算執行的操作:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM