代码如下:
#encoding=utf-8
print '中国'
#带版本号的文件名
import os
def VersionFile(file_spec, vtype='copy'):
import os, shutil
if os.path.isfile(file_spec):
if vtype not in ('copy','rename'):
raise ValueError,'Unknown vtype %r' %(vtype,)
n, e = os.path.splitext(file_spec)
if len(e) == 4 and e[1:].isdigit():
num = 1 + int(e[1:])
root = n
else:
num = 0
root = file_spec
for i in xrange(num,1000):
new_file = '%s.%03d' %(root,i)
if not os.path.exists(new_file):
if vtype == 'copy':
shutil.copy(file_spec, new_file)
else:
os.rename(file_spec, new_file)
return True
raise RuntimeError,'Failed'
return False
testfile = 'test.abc'
open(testfile,'w').close()
print VersionFile(testfile)
print VersionFile(testfile)
print VersionFile(testfile)
for x in ('','.000','.001','.002'):
os.unlink(testfile + x)
print VersionFile(testfile)
打印结果如下:
中国
True
True
True
False