ValueError: I/O operation on closed file but the syntax in another area of my code is the same and works correctly to save the file

Viewed 19

When attempting to save the updated excel workbook, an error occurs: ValueError: I/O operation on closed file. I have a similar block of code almost identical to this one which works properly and saves the changes to the excel workbook without issue using the same syntax. So I am not sure where the error is occurring.

#Prepares AUDIT RAW data to be copied into FIPA report from other workbooks
print("Audit Raw Data filepath aka name (Path 3):", glob.glob('v_cr_amp_dcp_audit_monitoring_*.csv')) #Test to check if filepath is correctly pulled
path3 = glob.glob('v_cr_amp_dcp_audit_monitoring_*.csv') #Sets path for AUDIT RAW data
path3 = ''.join(path3) #converts object from list to string
print("Audit Raw Data filepath aka name(Path 3):",path3)

print()

print("FILE CONVERSION!!!!!!!!")
#CONVERT CSV TO EXCEL
import pandas as pd
df_new = pd.read_csv(path3) # Reading the csv file
# saving xlsx file
GFG = pd.ExcelWriter('v_cr_amp_dcp_audit_monitoring_.xlsx')
df_new.to_excel(GFG, index=False)
print("csv to excel file path and name (path 3):", path3)
GFG.save()
print("FILE CONVERSION!!!!!!!!!")

print()
path3 = glob.glob("v_cr_amp*.xlsx")#Sets path for AUDIT RAW data after conversion
path3 = ''.join(path3)#converts object from list to string
workbook3 = openpyxl.load_workbook(path3) #Opens the AUDIT RAW workbook
sheetnames3 = workbook3.sheetnames #assigns variable to sheetname dictionary object
print("Audit Raw Data sheetnames:", sheetnames3) #Testing sheet name function
#Prepare target sheet (Audit raw) and source sheet (v_cr_amp_dcp_audit_monitoring...xlsx)
wb_target = workbook #Designates workbook where the data will move to
print("workbook target sheetnames:", wb_target.sheetnames)
target_sheet = wb_target['Audit Raw'] #Designates worksheet where the data will move to
wb_source = workbook3 #Designates workbook where the data will move from
print("workbook source sheetnames:", wb_source.sheetnames)
source_sheet = wb_source['Sheet1'] #Designates worksheet where the data will move from
copy_sheet(workbook3['Sheet1'], workbook['Audit Raw']) #Invokes copy_sheet() definition to copy data into FIPA report raw tab
path = './Test_Audit_Raw.xlsx'
workbook = wb_target
workbook.save(path)

ERROR NOTIFICATION

2845 
   2846     try:
-> 2847         fp.seek(0)
   2848     except (AttributeError, io.UnsupportedOperation):
   2849         fp = io.BytesIO(fp.read())

ValueError: I/O operation on closed file.
0 Answers
Related