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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With