【问题标题】:For some reason odd reason i can't seem to make my code write in the txt file出于某种奇怪的原因,我似乎无法让我的代码写入 txt 文件
【发布时间】:2022-11-27 17:22:09
【问题描述】:

所以我写了这段代码,我希望计算机打开一个文件并在其中写入用户对我问他的问题的回答,但是当我打开 txt 文件时它是空的。

import os 

Welcome = input("Hi my name is Steve. Do you have an account at Steve? ANSWER WITH JUST A YES OR NO ")

def register():
    name = input("First name: ")
    last_name = input("Last name: ")
    Email = input("Email: ")
    ussername = input("Username: ")
    password = input("Password: ")
def login():
    ussername = input("Username: ")
    password = input("Password: ")

if Welcome == "yes":
    login()
else: 
    register()

if Welcome == "no" or "No":
    with open("userinfo.txt", "w") as file:
        file.write(register())


【问题讨论】:

    标签: python file module


    【解决方案1】:

    您的文件是空的,因为您没有向其中写入任何内容。您的 register() 函数不返回任何内容,因此没有任何内容写入文件。

    也许您想添加类似

    return f"{name} {last_name}"
    

    到你的register() func 的结尾?至少应该将某些内容写入您的输出文件。

    另外,你在if Welcome == "no" or "No":中有逻辑错误

    我会把它改成:

    if Welcome.lower() == "no":
    

    这修复了你的逻辑错误。

    你写的那一行可以写成:

    if Welcome == "no" or Welcome == "No":
    

    【讨论】:

      【解决方案2】:

      您没有向文件写入任何内容。我修改了代码以将响应添加到文件,还更改了代码以使其更准确。

      welcome = input("Hi my name is Steve. Do you have an account at Steve? ANSWER WITH JUST A YES OR NO ")
      
      
      def register():
          first_name = input("First name: ")
          last_name = input("Last name: ")
          email = input("Email: ")
          username = input("Username: ")
          password = input("Password: ")
      
          with open("userinfo.txt", "w") as file:
              file.write(f"{first_name}
      {last_name}
      {email}
      {username}
      {password}")
      
      
      def login():
          username = input("Username: ")
          password = input("Password: ")
      
      
      if welcome.upper() == "YES":
          login()
          print("LOGGED IN!")
      elif welcome.upper() == "NO":
          register()
          print("REGISTRATION SUCCESFULL!")
      else:
          print("WRONG INPUT!")
      

      【讨论】:

        猜你喜欢
        • 2017-03-16
        • 2022-01-20
        • 2013-01-15
        • 2014-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-05
        相关资源
        最近更新 更多