使用Python对文件名进行版本控制

2024-04-26 10:31:55 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,当我下载一个文件时,它应该检查文件是否存在。如果不存在,则使用版本0重命名文件;否则,如果存在,则使用下一个迭代版本重命名文件(例如,它应该是file-name-version-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

上面的代码只有在下载文件后才能工作,它将显式检查并使用版本(如果存在)重命名该文件。在

我希望以这种方式它应该隐式检查。在


Tags: 文件namein版本newifosok
1条回答
网友
1楼 · 发布于 2024-04-26 10:31:55

使用glob检查目标目录中的文件:

我无法测试这段代码,暂时将其视为伪代码。但是,一旦你将方法正确地集成到你的程序中,这就可以完成任务了。在

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

相关问题 更多 >