I’m following a tutorial in a textbook, “Starting out with python 2nd edition” and I’m getting a traceback with this exercise in IDLE 3.2. I can’t seem to figure out the issue, it allows me to input the number of sales then only 1 sales amount it the echos “Data written to sales.txt.” then displays the prompt for day 2 but any amount entered causes a traceback:
line 118, in main
sales_file.write(str(sales) + ‘\n’)
ValueError: I/O operation on closed file.
Code:
def main():
num_days = int(input('For how many days do ' + \
'you have sales? '))
sales_file = open('sales.txt', 'w')
for count in range(1, num_days + 1):
sales = float(input('Enter the sales for day #' + \
str(count) + ': '))
sales_file.write(str(sales) + '\n')
sales_file.close()
print('Data written to sales.txt.')
main()
You are closing the file inside the for-loop. Next time through the loop when you write to the file, you are trying to write to a file that has been closed, hence the error message that says
I/O operation on closed file..Move the line
to after the print statement at the bottom of the for-loop, but indent it at the level of the
for. That will close the file only once after the loop (rather than repeatedly), i.e., when you are done with it at the end of your program.Like this:
A better approach would be to use the
withstatement as it will automatically close the file for you when you are done. So you could say