0

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 ?

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.