0

I am writing a small script. The script creates .txt files. I do not want to replace existing files. So what I want python to do is to check if the file already exists. If it does not it can proceed. If the file does exists I would like python to increment the name and than check again if the file already exists. If the file does not already exist python may create it. EXAMPLE: current dir has these files in it:

file_001.txt

file_002.txt

I want python to see that the two files exists and make the next file:

file_003.txt

creating files can be done like this:

f = open("file_001.txt", "w")
f.write('something')
f.close()

checking if a file exists:

import os.path
os.path.isfile(fname)
Community
  • 1
  • 1
Vader
  • 6,335
  • 8
  • 31
  • 43

2 Answers2

2

If you want to check whether it's both a file and that it exist then use os.path.exists along with os.path.isfile. Or else just the former seems suffice. Following might help:

import os.path as op
print op.exists(fname) and op.isfile(fname)

or just print op.exists(fname)

Bleeding Fingers
  • 6,993
  • 7
  • 46
  • 74
  • I also want python to find out which is the next file to be created in the sequence and create it. – Vader Jan 23 '14 at 21:52
1

Here is some code that will get the job done, I answered it myself.

import os.path

def next_file(filename):
    """
    filename: string. Name only of the current file
    returns: string. The name of the next file to be created
    assumes the padding of the file is filename_001.txt The number of starting zeros does   not not matter
    """
    fill_exists = True
    current = '001'
    padding = len(current)  # length of digits
    file = '{}_{}.txt'.format(filename, current)  # the actual name of the file, inlc. extension
    while fill_exists:
        if not os.path.isfile(file):  # if the file does not already exist
            f = open(file, 'w')  # create file
            f.write(filename)
            f.close()
            return 'Created new file: {}_{}.txt'.format(filename, current)  # shows the name of file just created
        else:
            current = str(int(current)+1).zfill(padding)  # try the next number
            file = '{}_{}.txt'.format(filename, current)
Vader
  • 6,335
  • 8
  • 31
  • 43