使用 Python 控制文件名 [英] Versioning file name using Python

查看:24
本文介绍了使用 Python 控制文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上当我下载文件时,它应该检查文件是否存在.如果不退出,则用版本 0 重命名文件,否则,如果存在,则用下一个迭代版本重命名文件(例如,它应该是 file-name-version-1)

Basically when I download a file, it should check whether the file exists or not. If not exits rename the file with the version-0 else if exists rename the file with the next iterating version (eg- it should be 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

以上代码只有在下载文件后才能工作,它会明确检查并使用版本重命名文件(如果存在).

Above code is going to work only after downloading the file it will explicitly check and Renaming the file with version if exists.

我希望它应该以这种方式进行隐式检查.

I want in such a way it should check implicitly.

推荐答案

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

Use glob to check for the file in your target directory:

我无法测试此代码,暂时将其视为伪代码.但是,一旦您将该方法正确集成到您的程序中,这应该可以完成工作.

I havent been able to test this code, consider it as pseudocode for now. But this should do the job once you integrate the method properly into your program.

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

这篇关于使用 Python 控制文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆