谁能帮我弄一下蟒蛇.替换文本文件中的字符串



我是相当新的python,我试图创建一个登录系统,你可以改变你的用户名。我已经通过多个论坛,但找不到任何工作。你能告诉我代码出了什么问题吗?它出现的错误是:AttributeError: '_io。TextIOWrapper'对象没有属性'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))

filefile对象,不是字符串!如果需要文件的内容,执行:

s = file.read()

,它将给你一个字符串的内容(它有一个方法replace)。

要把它写回同一个文件,你必须以写模式再次打开它:

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

file应替换为字符串

variable = file.read()

您正在尝试在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))

最新更新