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.
CodePudding user response:
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.
while True:
num = int(input("enter a number, to stop enter 0"))
if num == 0:
break
with open('number_list.txt', 'a') as f:
f.write(str(num))
# if you want it like this
# f = open('number_list.txt', 'a')
# f.write(str(num))
# f.close()
CodePudding user response:
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 the with
statement. Even if the writing process throws an exception, the file will surely close.
while True:
num = int(input("Enter a number, to stop enter 0:"))
if num == 0: break
with open('number_list.txt', 'a') as f:
f.write(str(num))
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.
nums = []
while True:
num = int(input("Enter a number, to stop enter 0:"))
if num == 0:
break
else:
nums.append(num)
with open('number_list.txt', 'a') as f:
f.writelines(nums)