2017-10-22 4 views
1

基本的にファイルをダウンロードするとき、ファイルが存在するかどうかを確認する必要があります。終了はしてファイル名を変更しない場合は、バージョン0他に次の反復バージョンとファイルの名前を変更存在する場合Pythonを使用したファイル名のバージョン

ここ

は、私が試したものである(EG-それはファイル名バージョン-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 
関連する問題