打开文件的代码,使用循环从用户获取数字并将数字写入文件,然后关闭文件
我正在尝试解决以下问题:
编写执行以下操作的代码:使用文件名number_list.txt打开输出文件,使用循环从用户获取数字,并将数字写入文件,然后关闭文件。
这是我所拥有的:
while True:
num = int(input("enter a number, to stop enter 0"))
myflie = open("number_list.txt", "w")
myflie.write(str(num))
if num == 0:
break
myflie.close()
代码不会给我任何错误,但是当我检查文件时,只有一个数字会写入其中。
I'm trying to solve the following problem:
Write code that does the following: opens an output file with the filename number_list.txt, uses a loop to get numbers from the user, and writes the numbers to the file, then closes the file.
Here's what I have:
while True:
num = int(input("enter a number, to stop enter 0"))
myflie = open("number_list.txt", "w")
myflie.write(str(num))
if num == 0:
break
myflie.close()
The code doesn't give me any errors, but when I check the file, only one number gets written to it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
a
在不首先删除内容的情况下写入文件,如果您不希望写入“ 0”,请在写操作之前移动检查。Use
a
to write to a file without deleting the contents first, also move the check before the write operation if you don't want '0' to be written as well.无论何时写入文件,
"w"
模式都会覆盖文件的内容。似乎您想附加到它,因此,使用模式"a"
。另外,使用with
语句执行文件操作。即使写入过程抛出异常,文件也肯定会关闭。如果您认为每次循环运行一次文件操作太多,您可以将输入附加到列表中,并在用户跳出循环后执行 writelines 操作。
The mode
"w"
overwrites the contents of the file whenever you write to it. It seems as if you want to append to it, and so, use the mode"a"
. Also, do file operations using with thewith
statement. Even if the writing process throws an exception, the file will surely close.If you think having a file operation for every run of the loop is too much, you can append the inputs in a list and do a
writelines
after the user breaks out of the loop.