Pandas to_csv() checking for overwrite
Try the following:
import globimport pandas as pd# Give the filename you wish to save the file tofilename = 'Your_filename.csv'# Use this function to search for any files which match your filenamefiles_present = glob.glob(filename)# if no matching files, write to csv, if there are matching files, print statementif not files_present: pd.to_csv(filename)else: print 'WARNING: This file already exists!'
I have not tested this but it has been lifted and compiled from some previous code which I have written. This will simply STOP files overwriting others. N.B. you will have to change the filename variable yourself to then save the file, or use some datetime variable as you suggested. I hope this helps in some way.
Based on TaylorDay's suggestion I made some adjustments to the function. With the following code you are asked whether you would like to overwrite an existing file. If not, you are allowed to type in another name. Then, the same write-function is called, which will again check whether the new_filename
exists.
from os import pathimport pandas as pddef write_csv_df(path, filename, df): # Give the filename you wish to save the file to pathfile = os.path.normpath(os.path.join(path,filename)) # Use this function to search for any files which match your filename files_present = os.path.isfile(pathfile) # if no matching files, write to csv, if there are matching files, print statement if not files_present: df.to_csv(pathfile, sep=';') else: overwrite = raw_input("WARNING: " + pathfile + " already exists! Do you want to overwrite <y/n>? \n ") if overwrite == 'y': df.to_csv(pathfile, sep=';') elif overwrite == 'n': new_filename = raw_input("Type new filename: \n ") write_csv_df(path,new_filename,df) else: print "Not a valid input. Data is NOT saved!\n"