0

I want create file safely in python2.7

import os
import sys
logname = "logfile"
f = open(logname, 'w')
sys.stdout = f
print "file created with file name {}".format(logname)
f.close()

Above script will overwrite if file is exist. I dont want to recreate it.

Say if file name "logfile" already exist, try to create with "logfile1" name.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
gopinara
  • 51
  • 8
  • Can't you just check if the file exists before trying to create it? – Carcigenicate Sep 10 '17 at 14:32
  • Possible duplicate of [Safely create a file if and only if it does not exist with python](https://stackoverflow.com/questions/10978869/safely-create-a-file-if-and-only-if-it-does-not-exist-with-python) – Peter Wood Sep 10 '17 at 14:38
  • You could open in `a` mode for appending to an existing file or create if not exists. – OneCricketeer Sep 10 '17 at 14:42

1 Answers1

0

You can use os.path.isfile to check if the file already exists

if os.path.isfile(logname):
    logname = increment(logname) # increment the filename
f = open(logname, 'w')
sys.stdout = f
print "file created with file name {}".format(logname)
f.close()

Depending on your naming conventions, there are multiple ways you could implement your increment function

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218