【问题标题】:Python: Open and write to a .txt filePython:打开并写入 .txt 文件
【发布时间】:2015-11-30 23:43:45
【问题描述】:

我是 python 新手,所以我正在尝试制作一个 ATM(我猜是模拟器)。其中一个功能是注册,因此我尝试将用户名保存在 .txt 文件中以供参考(当然稍后会提供密码),但由于某种原因它不起作用。

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

username = raw_input('> ')

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

它告诉我,该文件未打开以供写入。 顺便说一句,users.txt 文件与程序位于同一目录中。

【问题讨论】:

  • with open('filename','w') as f:。查看mode parameter in the open() function
  • 如果要写入脚本目录,先import osopen(os.path.join(os.path.basename(__file__), "users.txt"), "a")。这会根据脚本目录而不是用户当前的工作目录构建路径名。
  • 除非您希望每次运行都丢失数据,否则请使用a 而不是w

标签: python python-2.7


【解决方案1】:

我认为应该是:

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

【讨论】:

    【解决方案2】:

    你应该使用

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

    而不是

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

    希望这会有所帮助!

    【讨论】:

    • @Piethon 如果可行,您可以点击此答案附近的复选标记,将问题标记为已解决
    【解决方案3】:

    鉴于您正在调用 f.write(username, "a") 并且文件 write() 只接受一个参数 - 要写入的文本 - 我猜您打算将 "a" 追加到文件中? p>

    这在open() 调用中进行;告诉您使用open(name, "w") 的其他答案是不好的建议,因为它们会覆盖现有文件。您可能还想在用户名之后写一个换行符,以保持文件整洁。例如

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

    【讨论】:

      【解决方案4】:

      您必须以写入模式打开文件。见the documentation for open

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

      【讨论】:

        猜你喜欢
        • 2017-08-26
        • 1970-01-01
        • 1970-01-01
        • 2017-11-01
        • 2022-07-20
        • 2020-12-07
        • 1970-01-01
        • 2017-05-13
        • 1970-01-01
        相关资源
        最近更新 更多