【问题标题】:Can someone help me with this Python. Replacing string in txt file [closed]有人可以帮我处理这个 Python。替换txt文件中的字符串[关闭]
【发布时间】:2017-03-31 06:10:58
【问题描述】:

我对 python 很陌生,我正在尝试创建一个登录系统,您可以在其中更改您的用户名。我已经通过多个论坛,但找不到任何有效的方法。你能告诉我代码出了什么问题吗?它出现的错误是:AttributeError: '_io.TextIOWrapper' object has no attribute 'replace'。如果这有帮助。以下是代码:

print("What would you like your username to be changed to?")
C2 = input()
file = open("Info.txt", 'r+')
file.write(file.replace(A1, C2))

【问题讨论】:

  • file 是一个文件,而不是一个字符串。鉴于您将其命名为 file,尚不清楚为什么会出现意外!
  • 几个问题,“A1”未定义,您正在尝试对文件对象进行字符串替换。不确定您如何将数据存储在文件中,但您可以按行/标记读取文件,并将所需行的用户名替换为新用户名。

标签: python string replace io


【解决方案1】:

filefile 对象,而不是字符串!如果您想要文件的内容,请执行以下操作:

s = file.read()

它会将其内容作为字符串提供给您(它有一个方法replace)。

要将其写回同一个文件,您必须以写入模式再次打开它:

file = open("Info.txt", 'w')
file.write(s.replace(A1, C2))
file.close()

【讨论】:

  • 成功调用replace()后,您仍需要重写文件以包含新内容。
  • @JohnGordon 非常正确,我详细阐述了一些。一旦最初的错误消失,OP就会自己遇到(并且可能试图解决)这个问题:)
【解决方案2】:

file 应替换为字符串。

variable = file.read()

【讨论】:

    【解决方案3】:

    您正在尝试在 file 对象上调用 replace。您收到该错误是因为文件对象没有名为 replace 的属性。

    如果将文件内容读入字符串,则可以替换值并重写文件。

    print("What would you like your username to be changed to?")
    
    C2 = input()
    
    contents = ""
    with open("Info.txt", 'r') as blah:
        contents = blah.read()
    
    with open("Info.txt", 'w') as blah:
        blah.write(contents.replace(A1, C2))
    

    【讨论】:

      猜你喜欢
      • 2021-01-04
      • 2023-04-01
      • 1970-01-01
      • 2015-11-24
      • 2020-08-26
      • 2012-06-28
      • 2016-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多