Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ValueError I/O operation on closed file

I know this sounds a common error which has been asked multiple times on stackoverflow. However, I am pretty sure my issue is new as I read through almost the related topics.

I have two files as follows:

ALL_USER_PATH = 'all.csv'
NEW_USER_PATH = 'new.csv'

I open the "all" file for reading first

with open(ALL_USER_PATH, "r") as f:
    df = pd.read_csv(f) #pd is pandas
    f.close()

Next, I delete the content of the "new" file and get ready to write new data to it

if os.path.isfile(NEW_USER_PATH):
    os.remove(NEW_USER_PATH)

Write to it and it works fine

with open(NEW_USER_PATH, "a") as csv_n:
    #writer_n is to write new users
    writer_n = csv.writer(csv_n, delimiter=",", lineterminator='\n')
    for user in customer_records:         
        if checkExistence(df): # a method I wrote before
            continue
        else:    
            writer_n.writerow([data_to_be_written])

Next, I delete the "all" file and write new data to it

if os.path.isfile(ALL_USER_PATH):
    os.remove(ALL_USER_PATH)

with open(ALL_USER_PATH, "a") as csv_a:
    writer_a = csv.writer(csv_n, delimiter=",", lineterminator='\n')

    for user in customer_records:
        writer_a.writerow([all_data_to_be_written])

The error

"ValueError i/o operation on closed file"

is thrown herein at the last line to write data to the "all" file. I think it is because I opened it before, but I do remember to close it after reading the data, don't I? Could somebody please let me know what the problem is?

like image 721
Duy Bui Avatar asked Jan 07 '23 02:01

Duy Bui


1 Answers

I also had that error but found another question with an answer and it worked.

After you leave the indented block under with open (csv file.csv) as csv: it will close the file.

with open('ALL_USER_PATH','a') as csv_a:
    writer_a = csv.writer(csv_n, delimiter=",", lineterminator='\n')
    # Here the file stays open
# Here the file is closed

I hope I managed to help.

like image 104
TheOneWhoLikesToKnow Avatar answered Jan 16 '23 18:01

TheOneWhoLikesToKnow