简体   繁体   English

Python:打开并写入.txt文件

[英]Python: Open and write to a .txt file

I'm new to python and so I'm trying to make an ATM (simulator I guess). 我是python的新手,所以我正在尝试制作ATM(我猜是模拟器)。 One of the functions is to register, and so I'm trying to save the usernames in a .txt file for reference (passwords will come later of course), but for some reason it won't work. 功能之一是注册,因此我试图将用户名保存在.txt文件中以供参考(当然,密码稍后会出现),但是由于某种原因,它将无法正常工作。

def atm_register():
print "To register, please choose a username."

username = raw_input('> ')

with open("users.txt") as f:
    f.write(username, "a")

It tells me, that the file is not open for writing. 它告诉我,该文件未打开可写入。 Btw, the users.txt file is in the same directory as the program. 顺便说一句,users.txt文件与该程序位于同一目录中。

我认为应该是:

open("users.txt","w")

You should use 你应该用

with open("users.txt","a") as f:
      f.write(username)

instead of 代替

with open("users.txt") as f:
     f.write(username, "a")

hope this helps! 希望这可以帮助!

You must open the file in write mode. 您必须以写入模式打开文件。 See the documentation for open 请参阅开放文档

open('users.txt', 'w') should work. open('users.txt', 'w')应该可以工作。

Given that you're calling f.write(username, "a") and file write() only takes one parameter - the text to write - I guess you intend the "a" to append to the file? 假设您正在调用f.write(username, "a")而文件write()仅采用一个参数-要写入的文本-我猜您打算将"a" 追加到文件中吗?

That goes in the open() call; 那在open()调用中进行; other answers telling you to use open(name, "w") are bad advice, as they will overwrite the existing file. 告诉您使用open(name, "w")其他答案是错误的建议,因为它们会覆盖现有文件。 And you might want to write a newline after the username, too, to keep the file tidy. 而且,您可能还想在用户名后写一个换行符,以保持文件整洁。 eg 例如

with open("users.txt", "a") as f:
    f.write(username + "\n")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM