Python,repl.it - 未使用 csv.writer 和 writer.writerow 将详细信息写入文件
Posted
技术标签:
【中文标题】Python,repl.it - 未使用 csv.writer 和 writer.writerow 将详细信息写入文件【英文标题】:Python, repl.it - details are not being written to file using csv.writer and 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()
【问题讨论】:
【参考方案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()
当下一个方法出现并尝试读取文件时,它将以这种方式包含预期的数据。
【讨论】:
"with open" 是一种自动关闭文件的功能/命令 - 还是我错了? 谢谢@Anon Coward - 喜欢看这个相关的上下文问题:) ***.com/questions/66447589/…【参考方案2】:我可能错了,但你需要writerows
而不是writerow
,因为writerows
像你一样接受列表,writerow
接受列。
Like in this post
【讨论】:
Quoting the accepted answer 来自您链接的帖子:“您使用的是writer.writerows()
,末尾带有s
。该方法需要一个列表列表”。他们都接受列表。 writer.writerow()
需要一个字符串列表,而writer.writerows()
需要一个字符串列表。以上是关于Python,repl.it - 未使用 csv.writer 和 writer.writerow 将详细信息写入文件的主要内容,如果未能解决你的问题,请参考以下文章
从 PyCharm 导入到 Repl.it 后 Python 代码不起作用(ParseError: bad input)
python 由robturtle创建的DFA - https://repl.it/EzaW/47
python 由robturtle创建的DFA - https://repl.it/EzaW/28