string generator

Peter Hansen peter at engcorp.com
Sun Jun 2 17:42:38 EDT 2002


Gold Fish wrote:
> 
> I like to create a list of file automatical based on series. For example
> user input the number of file say 5. So i want to generate the file
> according to this range , this mean the generated files could be
> filename1
> filename2
> filename3
> filename4
> filename5
> I using the for loop like that
> 
> for file in range(5):
>         lis = [file]
>         string.join('filename',lis[1:])
> how can it didn't work. I am confusing how to do it.

The 'for' statement is giving you five passes through the
loop, with 'file' set to the integer values 0, 1, ... 4.
You put them each time inside a list called 'lis', then
take a slice of the list *after* the only element you've
put in it.  Even if it worked, you would just be throwing
away the results of the string.join() since you don't
do anything with it.

Presumably you are getting an AttributeError as a result.
Please *always* post the trackback you get so we know what
the exact problem is.  Don't make us guess.

Anyway, what you want is more like this:

for fileIndex in range(5):
    fileName = 'filename%s' % fileIndex
    print fileName

Now if you want to actually create files with those
names, you'll need "file = open(fileName, 'w')" and
more.

Have you gone through the complete tutorial yet?  Something
tells me you're missing some of the basics still.

-Peter



More information about the Python-list mailing list