【问题标题】:Writing input of a user into a file within an if-statement. (python)将用户的输入写入 if 语句中的文件。 (Python)
【发布时间】:2020-09-17 17:28:33
【问题描述】:

我正在尝试从用户那里获取输入并将其放入文件中 在 if 语句中。当我运行代码时,它运行顺利,但它没有将输入写入 names.txt 文件。这是代码

if click.confirm('Are you a new user?', default=True):
    user_name = input("Welcome. What's your name? ")
    names_file = open("names.txt", "a")
    names_file.write(user_name)
else:
    print("Welcome back")

【问题讨论】:

  • 你有什么问题?
  • 它不会将输入写入 names.txt 文件。
  • 你需要像f.close()一样关闭file writing
  • 您是否在 CMD 或 IDE 中遇到此问题?

标签: python-3.x file


【解决方案1】:

在 pythin 3.x 上尝试这个脚本的简单构建

if True:
    f = open('test.text', 'w')
    f.write('Hello World from python file write')
    f.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多