Python:帮助计数和写文件

-1 投票
4 回答
2393 浏览
提问于 2025-04-15 20:09

可能重复的问题:
Python:我该如何创建顺序文件名?

有人建议我使用一个单独的文件来作为计数器,这样我就可以给我的文件起顺序的名字,但我不太明白该怎么做。我需要我的文件名有顺序的数字,比如 file1.txt、file2.txt、file3.txt。希望能得到一些帮助!

编辑:
我犯了个错误,忘了说代码执行时只会生成一个文件,需要一种方法来生成一个新的文件,并且文件名要不同。

更多编辑:
我基本上是在截屏,然后想把它写入一个文件,我希望能多截几张,而不会覆盖之前的文件。

4 个回答

0

像这样吗?

n = 100
for i in range(n):
  open('file' + str(i) + '.txt', 'w').close()
0

假设的例子。

import os
counter_file="counter.file"
if not os.path.exists(counter_file):
    open(counter_file).write("1");
else:
    num=int(open(counter_file).read().strip()) #read the number
# do processing...
outfile=open("out_file_"+str(num),"w")
for line in open("file_to_process"):
    # ...processing ...
    outfile.write(line)    
outfile.close()
num+=1 #increment
open(counter_file,"w").write(str(num))
4

可能还需要更多的信息,但如果你想给文件按顺序命名,以避免名字冲突等问题,其实不一定需要一个单独的文件来记录当前的数字。我假设你是想不时地写一个新文件,并且需要编号来跟踪这些文件,对吧?

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

比如说(对于当前目录中的文件):

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

不过,显然随着目录中文件数量的增加,这个过程会变得越来越慢,所以这也取决于你预计会有多少个文件。

撰写回答