Python:如何创建连续的文件名?

发布于 2024-08-24 10:45:16 字数 101 浏览 1 评论 0原文

我希望我的程序能够以顺序格式写入文件,即:file1.txt、file2.txt、file3.txt。它仅意味着在执行代码时写入单个文件。它不能覆盖任何现有文件,并且必须创建它。我很困惑。

I want my program to be able to write files in a sequential format, ie: file1.txt, file2.txt, file3.txt. It is only meant to write a single file upon execution of the code. It can't overwrite any existing files, and it MUST be created. I'm stumped.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

却一份温柔 2024-08-31 10:45:16

两个选择:

  1. 计数器文件。

  2. 检查目录。

计数器文件

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

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

Two choices:

  1. Counter File.

  2. Check the directory.

Counter File.

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

count += 1

Each time you create a new file, you also rewrite the counter file with the
appropriate number. Very, very fast. However, it's theoretically possible to
get the two out of synch. in the event of a crash.

You can also make the counter file slightly smarter by making it a small piece of
Python code.

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

Then, when you update the file, you write a little piece of Python code: count = someNumber. You can add comments and other markers to this file to simplify your bookkeeping.

Check the directory.

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

Slower. Never has a synchronization problem.

_蜘蛛 2024-08-31 10:45:16

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

Or you could append the current system time to make unique filenames...

情魔剑神 2024-08-31 10:45:16

这是我实现此方法的方式:

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)

抱歉,如果上面的代码很糟糕

Here is the way I implemented this:

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)

Thanks to Darius Bacon for the natural sort functions(see his answer here: https://stackoverflow.com/a/341730)

Sorry if the above code is fugly

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文