2017-10-22 5 views
1

기본적으로 파일을 다운로드 할 때 파일이 존재하는지 여부를 확인해야합니다. 출구가있는 파일의 이름을 변경하지 않으면 버전 0 다른 다음 반복하는 버전으로 파일의 이름을 변경이있는 경우Python을 사용하여 파일 이름 버전 지정

여기

내가 시도한 것입니다 (예 -이 파일 이름 버전-1이되어야합니다) :

def VersionFile(file_spec, vtype='copy'): 
    import os, shutil 

    ok = 0 
    if os.path.isfile(file_spec): 
     # or do other error checking... 
     if vtype not in ('copy', 'rename'): 
      vtype = 'copy' 

     # determine root file name so the extension doesn't get longer and longer... 
     n, e = os.path.splitext(file_spec) 

     # is e an integer? 
     try: 
      num = int(e) 
      root = n 
     except ValueError: 
      root = file_spec 

     # find next available file version 
     for i in xrange(100): 
      new_file = '%s_V.%d' % (root, i) 
      if not os.path.isfile(new_file): 
       if vtype == 'copy': 
        shutil.copy(file_spec, new_file) 
       else: 
        os.rename(file_spec, new_file) 
       ok = 1 
       break 
    return ok 

if __name__ == '__main__': 
    # test code (you will need a file named test.txt) 
    print VersionFile('test.txt') # File is exists in the directory 
    print VersionFile('alpha.txt') # File not exists in the directory 

위의 코드는 파일을 다운로드 한 후에 만 ​​작동하며 명시 적으로 파일 버전을 확인하고 버전이있는 경우 이름을 바꿉니다.

암시 적으로 확인해야합니다.

답변

0

사용 글로브는 대상 디렉토리에있는 파일을 확인 : 나는이 코드를 테스트 지금은 의사로 간주 할 수 있었다 havent 한

. 그러나 일단 프로그램에 메서드를 제대로 통합하면이 작업을 수행해야합니다.

import glob 

currentVersion = glob.glob(yourFileName) 

if currentVersion == []:        #checks if file exists 
    download and saveAs version-0         #saves as original if doesnt exist 
else: 
    download and saveAs (fileName+(list(currentVersion[0])[-1] + 1) #if exists, gets the existing version number, and saves it as that number plus one