A.Safie
A.Safie

Reputation: 1

Python ValueError: I/O operation on closed file

import csv

shop_products=' '
total_price=0.00

RECIEPT_FILE=open('reciept.txt', 'wt')

while True:
    GTIN_code=input('Please enter the GTIN-8 code of the product that you would like to purchase or simply press the enter key if you do not')
    if GTIN_code == '':
      break
    shop_products=open('Product.csv', 'rt')
    data_in_file=csv.reader(shop_products)
    for row in data_in_file:
        for field in row:
            if field==GTIN_code: 
                quantity=int(input('How many of the products do you want to purchase'))
                subtotal_price=float(row[2])*quantity
                total_price=total_price+subtotal_price
                RECIEPT_FILE.write(row[0]+' '+row[1]+' '+str(quantity)+' '+'£'+row[2])
                RECIEPT_FILE.close()
RECIEPT_FILE.write('Your total price of all your purchases is '+str(total_price))
RECIEPT_FILE.close()

here i am trying to make a receipt by writing the GTIN-8 codes into a text file, but whenever I run the programme, it reports this error:

Traceback (most recent call last):
  File "C:\Users\Ahmed\Documents\Task 2 test code\Products reciept generator - Copy.pyw", line 20, in <module>
    RECIEPT_FILE.write(row[0]+' '+row[1]+' '+str(quantity)+' '+'£'+row[2])
ValueError: I/O operation on closed file.

I am working in python 3.2.

Upvotes: 0

Views: 2318

Answers (1)

Prune
Prune

Reputation: 77837

Look at the last line of your loop, third from the bottom: you close the file the first time you write to it. The next write you do is illegal.

Remove that line; let the last line of the program do your one and only close.

Upvotes: 1

Related Questions