在python中读取和写入文本文件的问题

我正在尝试获取输入并将输入写入文本文件以保存它。但是,我似乎无法将用户输入写入文本文件。这是我的代码:


SaveUsername = open(r"C:\Users\Ty\Desktop\Login_sys\SaveUsername.txt","w+")

SavePassword = open(r"C:\Users\Ty\Desktop\Login_sys\SavePassword.txt","w+")

NewUsername = input("Please enter a username: ")

NewPassword = input("Please enter a password: ")

SaveUsername.write(NewUsername)

print (SaveUsername.readline())

SavePassword.write(NewPassword)

print (SavePassword.readline())

我正在打印 readline 以查看代码是否被写入并且它从来没有。请帮助,谢谢。


红糖糍粑
浏览 100回答 3
3回答

弑天下

尝试这个with open(r"SaveUsername.txt","w+") as SaveUsername:    NewUsername = input("Please enter a username: ")    SaveUsername.write(NewUsername)with open(r"SavePassword.txt","w+") as SavePassword:    NewPassword = input("Please enter a password: ")    SavePassword.write(NewPassword)with open(r"SaveUsername.txt" as SaveUsername:    print (SaveUsername.readline())with open(r"SavePassword.txt") as SavePassword:    print (SavePassword.readline())

慕运维8079593

首先,您应该在写入文件后关闭文件,然后再读取更改。您还应该使用with open(...)它,因为它是一种更好的做法(出于多种原因)。这是您应该使用的代码:with open(r"C:\Users\Ty\Desktop\Login_sys\SaveUsername.txt", "w") as SaveUsername:    NewUsername = input("Please enter a username: ")    SaveUsername.write(NewUsername)with open(r"C:\Users\Ty\Desktop\Login_sys\SavePassword.txt", "w") as SavePassword:    NewPassword = input("Please enter a password: ")    SavePassword.write(NewPassword)with open(r"C:\Users\Ty\Desktop\Login_sys\SaveUsername.txt", "r") as SaveUsername:    print(SavePassword.readline())with open(r"C:\Users\Ty\Desktop\Login_sys\SavePassword.txt", "r") as SavePassword:    print(SavePassword.readline())

元芳怎么了

在阅读之前关闭文件并打开以供阅读。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python