Python create file safely -
i want create file safely in python2.7
import os import sys logname = "logfile" f = open(logname, 'w') sys.stdout = f print "file created file name {}".format(logname) f.close()
above script overwrite if file exist. dont want recreate it.
say if file name "logfile" exist, try create "logfile1" name.
you can use os.path.isfile
check if file exists
if os.path.isfile(logname): logname = increment(logname) # increment filename f = open(logname, 'w') sys.stdout = f print "file created file name {}".format(logname) f.close()
depending on naming conventions, there multiple ways implement increment
function
Comments
Post a Comment