未使用csv.writer和writer.writerow将Python、repl.it详细信息写入文件

2024-06-28 21:47:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的repl.it程序,请注意,该程序的注册部分(以前工作正常)已停止工作

它最后说“write to file”,但实际上的write rows命令被跳过,因为没有任何内容写入文本文件

整个节目都在这里:

https://repl.it/@oiuwdeoiuas/Matchmakingskills-1

代码的相关部分如下所示,尽管可能存在其他因素(因此提供了整个代码)

def register():
    print("===Register====")
    print("First things first, sign up and tell us a little about yourself")
    with open("dating.txt","a") as fo: 
        writer=csv.writer(fo)        
        firstname=input("Enter first name:")
        lastname=input("Enter last name:")
        username=firstname+lastname[0]+"bird"
        print("Your automatically generated username is:",username)
        password=input("Enter password:")
        gender=input("Enter gender")
        email=input("Enter email:")
        dob=input("Enter date of birth in format dd/mm/yy:")
        beliefs=input("Enter beliefs")
        strengthslist=["patience","efficiency","sensitivity","frankness","submissiveness","leadership","timekeeping","laidback"]
        print(strengthslist)
        strengths=input("Enter your top strength: (select from the above list)")
        contactcount=0
        writer.writerow([username,password,firstname,lastname,gender,email,dob,beliefs,strengths,contactcount])
        print("written to file")
        mainmenu()

Tags: 程序inputemailusernameitpasswordfirstnamerepl
2条回答

我可能错了,但是您是否需要writerows而不是writerow,因为writerows接受列表就像您的列表一样,并且writerow接受列

Like in this post

您正在尝试读取仍处于打开状态的文件:

def register():
    # ...
    with open("dating.txt","a") as fo: 
        # ...
        print("written to file")
        # At this point, "dating.txt" hasn't been written to
        # the next call to open it that occurs here will
        # see the state of the file either partially written, or before
        # the row is written at all
        mainmenu()

有几种解决办法。最快的方法是在此处缩进一级:

def register():
    # ...
    with open("dating.txt","a") as fo: 
        # ...
        print("written to file")
    # dating.txt has been closed now, it's safe to read it
    mainmenu()

当下一个方法出现并尝试读取文件时,它将以这种方式包含预期的数据

相关问题 更多 >