Python:帮助计数器和写文件 [英] Python: Help with counters and writing files

查看:313
本文介绍了Python:帮助计数器和写文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

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

我被建议使用一个单独的文件作为计数器给我的文件顺序文件名,但我不明白我会怎么做。我需要我的文件名具有序列号,如file1.txt,file2.txt,file3.txt。任何帮助表示赞赏!

编辑:
我的错误,我忘了说,代码使1文件执行时,需要一种方法,使新的单独的一个不同的文件名。

更多编辑:
我基本上是一个屏幕截图,并试图将其写入一个文件,我想可以采取多个不被覆盖。

解决方案

更多的信息可能是需要的,但如果你想顺序名称文件,以避免名称冲突等你不一定需要一个单独的文件来记录当前的号码。我假设你不时想写一个新的文件,编号来跟踪事情?

因此,给定一组文件,你想知道什么下一个有效的文件名将是。



类似于(对于当前目录中的文件):

< code $

 
import os.path


def next_file_name():
num = 1
而True:
file_name ='file%d.txt'%num
如果不是os.path.exists(file_name):
return file_name
num + = 1



很显然,随着目录中文件数量的增加,这个速度会变慢,您预期会有多少个文件。

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.

解决方案

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):

import os.path

def next_file_name(): num = 1 while True: file_name = 'file%d.txt' % num if not os.path.exists(file_name): return file_name num += 1

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.

这篇关于Python:帮助计数器和写文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆