How do I create a incrementing filename in Python?

后端 未结 12 2096
终归单人心
终归单人心 2020-11-28 05:45

I\'m creating a program that will create a file and save it to the directory with the filename sample.xml. Once the file is saved when i try to run the program again it over

12条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 06:23

    My 2 cents: an always increasing, macOS-style incremental naming procedure

    • get_increased_path("./some_new_dir").mkdir() creates ./some_new_dir ; then
    • get_increased_path("./some_new_dir").mkdir() creates ./some_new_dir (1) ; then
    • get_increased_path("./some_new_dir").mkdir() creates ./some_new_dir (2) ; etc.

    If ./some_new_dir (2) exists but not ./some_new_dir (1), then get_increased_path("./some_new_dir").mkdir() creates ./some_new_dir (3) anyways, so that indexes always increase and you always know which is the latest


    from pathlib import Path
    import re
    
    def get_increased_path(file_path):
        fp = Path(file_path).resolve()
        f = str(fp)
    
        vals = []
        for n in fp.parent.glob("{}*".format(fp.name)):
            ms = list(re.finditer(r"^{} \(\d+\)$".format(f), str(n)))
            if ms:
                m = list(re.finditer(r"\(\d+\)$", str(n)))[0].group()
                vals.append(int(m.replace("(", "").replace(")", "")))
        if vals:
            ext = " ({})".format(max(vals) + 1)
        elif fp.exists():
            ext = " (1)"
        else:
            ext = ""
    
        return fp.parent / (fp.name + ext + fp.suffix)
    
    

提交回复
热议问题