jonatr
jonatr

Reputation: 380

creating a output file when the output file exists in the path

How do I code in python the option that when the output file exists in the path, the output file will automatically be "originalname"+"_1" / "originalname"+"_2" and so on ?

Upvotes: 0

Views: 242

Answers (3)

FredL
FredL

Reputation: 981

Something like

import os.path

def getnewfilename(filename):
    testfile = filename
    i = 0
    while os.path.exists(testfile):
        i += 1
        testfile = "%s_%s" % (testfile, i) 

    return testfile

This should generate

filename
filename_1
filename_2

if you use %s_%3i" you should get

filename
filename_001
filename_002
filename_003

which will then list alphabetically (but have problems when i>=1000)

Upvotes: 2

Ben
Ben

Reputation: 52863

isfile checks for the existence of a file and goes down simlinks as well; you can use the full filepath.

if os.path.isfile(filename):
    do_something()

Upvotes: 0

Björn Pollex
Björn Pollex

Reputation: 76828

You can use os.path.exists to check if a file already exists. The rest is a simple loop that tries new filenames.

Upvotes: 2

Related Questions