【问题标题】:How to save a file with serial numbers following the last file name in the folder using python [duplicate]如何使用python [重复]保存文件夹中最后一个文件名后的序列号文件
【发布时间】:2023-01-10 15:25:42
【问题描述】:

我的目录中有以下顺序的文件:

COL_1001.png
COL_1002.png

下次我保存文件时,我希望它被保存为

COL_1003.png

我如何使用 python 程序执行此操作,因为我正在使用示例中给出的 shutil

    allfiles = os.listdir(src)
    
    c = 1001
    for f in allfiles:
        if f in files and len(selected_prop)>0:
            s = f
            s = f.split('.')
            s[0] = projCode + '_' + selected_prop[0] + '_COL.' + str(c)
            k = '.'.join(s)
            shutil.copy( src + '\\' + f, os.path.join(dst,k))
            c += 1

谢谢

卡尔蒂基

【问题讨论】:

  • 请编辑您的问题并包含所有代码以创建最小的工作示例。例如:if f in files and len(selected_prop)>0: 什么是filesselected_prop

标签: python shutil


【解决方案1】:

pathlibos使用起来简单多了。只需一点regex,您就可以做到。

import re
from pathlib import Path
from typing import Union


def get_next_name(dirpath: Union[Path, str]) -> str:
    """Finds the next name available in the directory supplied."""
    filename_pattern = re.compile(r"COL_(d+).png")
    filename_template = "COL_{}.png"
    minimum_number = 1001 - 1  # for the first to be 1001
    filenames_in_directory = tuple(
        dir_entry.name
        for dir_entry in Path(dirpath).iterdir()
        if dir_entry.is_file()
    )
    filename_matches = tuple(
        filename_match
        for filename_match in map(filename_pattern.fullmatch, filenames_in_directory)
        if filename_match
    )
    numbers_matches = tuple(
        int(filename_match.group(1))
        for filename_match in filename_matches
    )
    next_number = max(
        (minimum_number, *numbers_matches)
    ) + 1
    return filename_template.format(next_number)


name = get_next_name(".")
print(name)
Path(name).touch()
name = get_next_name(".")
print(name)
Path(name).touch()
name = get_next_name(".")
print(name)
Path(name).touch()

【讨论】: