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

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -