[Tutor] multiple file output

Jeff Shannon jeff at ccvcorp.com
Tue Sep 9 11:27:24 EDT 2003


Jimmy verma wrote:
> Thanks to everyone for their suggestions. Now i want to open the file 
> with names which are created dynamically.
> 
>     out = open('f[i].txt', 'w')
>     out.write(str)
>     out.close()
> 
> something like this where f[i] should be coming from some list f

You can use string formatting to create dynamic names.

names = ['john', 'paul', 'george', 'ringo']
for name in names:
     filename = 'beatles_%s.txt' % name
     outfile = file(filename, 'w')
     outfile.write(foo)
     outfile.close()

The % operator substitutes the contents of 'name' into the %s 
placeholder location -- %s stands for string, but you can also use %d 
(for decimal numbers), %x (for hex), and a variety of other formatting 
specifiers, including specifying a minimum length and a padding 
character.  Check the Python tutorial for "string formatting" to get 
more details.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Tutor mailing list