Python:如何创建顺序文件名?

时间:2010-03-08 11:12:27

标签: python filesystems

我希望我的程序能够以顺序格式编写文件,即:file1.txt,file2.txt,file3.txt。它只是在执行代码时编写单个文件。它不能覆盖任何现有文件,必须创建它。我很难过。

3 个答案:

答案 0 :(得分:4)

两种选择:

  1. 计数器文件。

  2. 检查目录。

  3. 计数器文件

    with open("thecounter.data","r") as counter:
        count= int( counter.read() )
    
    count += 1
    

    每次创建新文件时,也会使用。重写计数器文件 适当的数量。非常,非常快。但是,理论上可行 让两者失去同步。如果发生车祸。

    您还可以通过将计数器文件变成一小部分来使计数器文件更加智能化 Python代码。

    settings= {}
    execfile( "thecounter.py", settings )
    count = settings['count']
    

    然后,当您更新文件时,您会编写一小段Python代码:count = someNumber。您可以在此文件中添加注释和其他标记,以简化簿记。

    检查目录

    import os
    def numbers( path ):
        for filename in os.listdir(path):
            name, _ = os.path.splitext()
            yield int(name[4:])
    count = max( numbers( '/path/to/files' ) )
    
    count += 1
    

    慢。从来没有同步问题。

答案 1 :(得分:3)

或者您可以附加当前系统时间来制作唯一的文件名...

答案 2 :(得分:1)

以下是我实现此方法的方法:

import os
import glob
import re

#we need natural sort to avoid having the list sorted as such:
#['./folder1.txt', './folder10.txt', './folder2.txt', './folder9.txt']
def sorted_nicely(strings):
    "Sort strings the way humans are said to expect."
    return sorted(strings, key=natural_sort_key)

def natural_sort_key(key):
    import re
    return [int(t) if t.isdigit() else t for t in re.split(r'(\d+)', key)]

#check if folder.txt exists
filename = "folder.txt" #default file name

#if it does find the last count
if(os.path.exists(filename)):
        result = sorted_nicely( glob.glob("./folder[0-9]*.txt"))
        if(len(result)==0):
                filename="folder1.txt"
        else:
                last_result = result[-1]
                number = re.search( "folder([0-9]*).txt",last_result).group(1)
                filename="folder%i.txt"%+(int(number)+1)

感谢Darius Bacon的自然排序功能(见他的回答:https://stackoverflow.com/a/341730

很抱歉,如果上面的代码很难看