Python:如何创建连续的文件名?
我希望我的程序能够以顺序格式写入文件,即: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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
两个选择:
计数器文件。
检查目录。
计数器文件。
每次创建新文件时,您还会使用以下内容重写计数器文件
适当的数量。非常非常快。不过,理论上是可以的
让两者不同步。如果发生碰撞事故。
您还可以通过将计数器文件制作为一小部分来使其稍微智能一些
Python 代码。
然后,当您更新文件时,您将编写一小段 Python 代码:
count = someNumber
。您可以向该文件添加注释和其他标记以简化簿记。检查目录。
慢点。从来没有同步问题。
Two choices:
Counter File.
Check the directory.
Counter File.
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.
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.
Slower. Never has a synchronization problem.
或者您可以附加当前系统时间来制作唯一的文件名......
Or you could append the current system time to make unique filenames...
这是我实现此方法的方式:
感谢 Darius Bacon 的自然排序函数(请参阅他的答案:https://stackoverflow.com/a /341730)
抱歉,如果上面的代码很糟糕
Here is the way I implemented this:
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