views:

89

answers:

4

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.

A: 

Something like this?

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

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))
ghostdog74
A: 
John Montgomery
A: 
# 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).

Alex Martelli