Python:计数器和写入文件的帮助
可能的重复:
Python:如何创建连续文件名?
建议使用单独的文件作为计数器来为我的文件提供连续的文件名,但我不明白如何做到这一点。我需要我的文件名具有连续的数字,例如 file1.txt、file2.txt、file3.txt。任何帮助表示赞赏!
编辑: 我的错误,我忘了说代码在执行时会创建一个文件,并且需要一种方法来创建一个具有不同文件名的新的单独文件。
更多编辑: 我基本上正在拍摄屏幕截图并尝试将其写入文件,并且我希望能够拍摄多个屏幕截图而不被覆盖。
Possible Duplicate:
Python: How do I create sequential file names?
I was suggested to use a separate file as a counter to give my files sequential file names, but I don't understand how I would do that. I need my file names to have sequential numbers, like file1.txt, file2.txt, file3.txt. Any help is appreciated!
Edit:
My mistake, I forgot to say that the code makes 1 file when it's executed, and needs a way to make a new separate one with a different file name.
More Edit:
I am taking a screen shot basically and trying to write it to a file, and I want to be able to take more than one without it being overwritten.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可能需要更多信息,但如果您想按顺序命名文件以避免名称冲突等,则不一定需要单独的文件来记录当前编号。我假设您想时不时地编写一个新文件,并编号以跟踪事物?
因此,给定一组文件,您想知道下一个有效文件名是什么。
类似于(对于当前目录中的文件):
显然,随着目录中文件数量的增加,速度会变慢,因此这取决于您期望有多少文件。
More information probably is needed, but if you want to sequentially name files to avoid name clashes etc you don't necessarily need a separate file to record the current number. I'm assuming you want to write a new file from time to time, numbering to keep track of things?
So given a set of files, you want to know what the next valid file name would be.
Something like (for files in the current directory):
Obviously though as the number of files in the directory increases this will get slower, so it depends on how many files you expect there to be.
像这样的东西吗?
Something like this?
假设的例子。
Hypothetical example.
在 Python 2.5 中,您还需要第一行
from __future__ import with_statement
才能使用此代码示例;在 Python 2.6 或更高版本中,您不需要(您也可以使用比%
运算符更优雅的格式化解决方案,但这是一个非常小的问题)。In Python 2.5, you also need a first line of
from __future__ import with_statement
to use this code example; in Python 2.6 or better, you don't (and you could also use a more elegant formatting solution than that%
operator, but that's a very minor issue).