Python: Help with counters and writing files [dupl

2020-05-09 19:47发布

问题:

This question already has answers here:
Closed 8 years ago.

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.

回答1:

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.



回答2:

Something like this?

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


回答3:

Hypothetical example.

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:

# get current filenum, or 1 to start
try:
  with open('counterfile', 'r') as f:
    filenum = int(f.read())
except (IOError, ValueError):
  filenum = 1

# write next filenum for next run
with open('counterfile', 'w') as f:
  f.write(str(filenum + 1))

filename = 'file%s.txt' % filenum
with open(filename, 'w') as f:
  f.write('whatever you need\n')
  # insert all processing here, write to f

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