How to close a file in python

python

#1

Hi here is my code -
I am writing to csv and when i ran getting the below error

def CSVCreate(file_name):
now = datetime.datetime.now()
my_file = Path(“C:\Users\SJainOF2973\Desktop\LM_Girish\day19_11\Processsed_CSV.csv”)

dfr=pd.read_excel(file_name,sheet_name='CHANGE LOG',usecols=(0,1))
dfr['Updated_Date']=dfr['Date']
dfr=dfr.drop(['Date'],axis=1)
dfr['Processed_Date']=now
dfr['File_Name']=file_name

if not os.path.isfile('my_file'):
    dfr.to_csv(my_file, header='column_names')
          
else:
    dfr.to_csv(my_file, mode='a', header=False) 
my_file.close()    

CSVCreate(file_name)

Error:
AttributeError: ‘WindowsPath’ object has no attribute ‘close’

have tried providing my_file.close at the end but no luck.
Any leads

Thanks in Advance.
Sachin


#2

You need to open the file first and then close.
outfile = open(path+‘filename.csv’, ‘wb’); df.to_csv(outfile); oufile.close()


#3

You do not need to open/close the file in this case, you could use the my_file just to check if your file exists.

def CSVCreate(file_name):
     now = datetime.datetime.now()
     out_filename = “C:\Users\SJainOF2973\Desktop\LM_Girish\day19_11\Processsed_CSV.csv”
     my_file = Path(out_filename)
     dfr=pd.read_excel(file_name,sheet_name='CHANGE LOG',usecols=(0,1))
     dfr['Updated_Date']=dfr['Date']
     dfr=dfr.drop(['Date'],axis=1)
     dfr['Processed_Date']=now
     dfr['File_Name']=file_name

     if not my_file.is_file():
         dfr.to_csv(out_filename, header='column_names')
     else:
         dfr.to_csv(out_filename, mode='a', header=False) 


CSVCreate(file_name)