How do I code in python the option that when 开发者_如何学Pythonthe output file exists in the path, the output file will automatically be "originalname"+"_1" / "originalname"+"_2" and so on ?
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)
You can use os.path.exists
to check if a file already exists. The rest is a simple loop that tries new filenames.
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()
精彩评论