如何使用python更改文件名的一部分

2024-04-19 09:10:49 发布

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

我对python(以及一般的代码)是全新的,我一直无法在网上找到解决我的特定问题的方法。我目前正在创建一个工具,允许用户将文件保存到网络位置。文件将具有版本号。我想要的是有脚本自动版本之前,它保存。我已经完成了脚本的其余部分,但是我遇到的问题是自动版本控制。以下是我目前掌握的情况:

import re
import os

def main():
    wip_folder = "L:/xxx/xxx/xxx/scenes/wip/"  
    _file_list = os.listdir('%s' % wip_folder)

    if os.path.exists('%s' wip_path):
        for file in _file_list:
            versionPattern = re.compile('_v\d{3}')
            curVersions = versionPattern.findall('%s' % wip_folder)
            curVersions.sort()
            nextVersion = '_v%03d' % (int(curVersions[-1][2:]) + 1)
        return nextVersion
    else:
        nextVersion = '_v001'

    name = xxx_xxx_xx
    name += '%s' nextVersion
    name += '_xxx_wip

我应该指出main()将由另一个模块中的QPushbutton调用。此外,wip\ U路径中很可能包含单个文件的多个版本。因此,如果在wip\ U路径中有10个版本的文件,则此保存应为v011。如果这个问题没有意义,我道歉。任何帮助都将不胜感激。谢谢您!你知道吗


Tags: 文件nameimport版本re脚本osmain
1条回答
网友
1楼 · 发布于 2024-04-19 09:10:49

你根本不需要使用re,编程是为了简化,你把它复杂化了!我选择返回,但是这个函数中的任何内容都可以更改为您需要它具体执行的任何操作!看看评论,祝你好运!你知道吗

def getVersioning(path):
    #passing path

    count = 1 #init count
    versionStr = 'wip_path_v'
    try: #in case path dosen't exist
        for i in os.listdir(path): #loop thorough files in passed dir
            if versionStr in i: #check if files contain default versioning string e.g. wip_path_V or any other (used in case other files are in the same dir)
                count += 1 #incriment count
    except:
        os.mkdir(path) #makedir if one does not exist for future use

    newName = versionStr + str(count) #new versioning file name
    return newName #return new versioning name

print getVersioning('tstFold')

相关问题 更多 >