【问题标题】:Python, repl.it - details are not being written to file using csv.writer and writer.writerowPython,repl.it - 未使用 csv.writer 和 writer.writerow 将详细信息写入文件
【发布时间】:2021-06-01 11:26:36
【问题描述】:

我有以下 repl.it 程序,并注意该程序的注册部分,之前运行良好,已停止运行。

它到最后说“写入文件”,但不知何故实际的 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()

【问题讨论】:

    标签: python csv file write


    【解决方案1】:

    您正在尝试读取仍然打开的文件:

    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()
    

    有几个解决方案。最快的是在此处将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()
    

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

    【讨论】:

    【解决方案2】:

    我可能错了,但你需要writerows 而不是writerow,因为writerows 像你一样接受列表,writerow 接受列。

    Like in this post

    【讨论】:

    • Quoting the accepted answer 来自您链接的帖子:“您使用的是writer.writerows(),末尾带有s。该方法需要一个列表列表”。他们都接受列表。 writer.writerow() 需要一个字符串列表,而writer.writerows() 需要一个字符串列表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 2012-07-14
    • 2023-01-09
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多