Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如何创建顺序文件名?_Python_Filesystems - Fatal编程技术网

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

Python:如何创建顺序文件名?,python,filesystems,Python,Filesystems,我希望我的程序能够以顺序格式编写文件,即:file1.txt、file2.txt、file3.txt。它只意味着在执行代码时编写一个文件。它不能覆盖任何现有文件,必须创建它。我被难住了。有两个选择: 计数器文件 检查目录 计数器文件 with open("thecounter.data","r") as counter: count= int( counter.read() ) count += 1 import os def numbers( path ): for fil

我希望我的程序能够以顺序格式编写文件,即:file1.txt、file2.txt、file3.txt。它只意味着在执行代码时编写一个文件。它不能覆盖任何现有文件,必须创建它。我被难住了。

有两个选择:

  • 计数器文件

  • 检查目录

  • 计数器文件

    with open("thecounter.data","r") as counter:
        count= int( counter.read() )
    
    count += 1
    
    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
    
    每次创建一个新文件时,也要使用 适当的数目。非常非常快。然而,理论上可以 让这两个不同步。万一发生车祸

    您还可以通过将计数器文件制作为一小片文件,使其稍微智能化 Python代码

    settings= {}
    execfile( "thecounter.py", settings )
    count = settings['count']
    
    然后,在更新文件时,编写一小段Python代码:
    count=someNumber
    。您可以在此文件中添加注释和其他标记,以简化记账

    检查目录

    with open("thecounter.data","r") as counter:
        count= int( counter.read() )
    
    count += 1
    
    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
    

    慢一点。从来没有同步问题。

    或者您可以附加当前系统时间以生成唯一的文件名…

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

    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提供的自然排序功能(请参见他的答案:)


    如果上述代码重复,则表示抱歉:。请编辑您的问题,不要简单地再次发布相同的问题。这不一样,我问如何实现计数器,我不知道如何做。我很抱歉弄错了,我只是觉得最好单独问一下,这样任何需要知道的人都可以通过搜索找到它。解决这个问题的经典方法是使用
    O|u create | O|u EXCEL
    标志创建一个文件,同时使用系统调用
    open
    。我已经编写了一个包,它利用了这一点,使创建这样的文件变得更容易:建议:为了避免任何TOCTTOU问题,使用create标志尝试打开文件,这将导致异常(如果文件已经存在),您可以捕获该异常,然后使用下一个数字重试。