[Tutor] question about looping.

Kent Johnson kent37 at tds.net
Fri Oct 6 11:53:44 CEST 2006


Doug Potter wrote:
> Hi,
> 
> I at trying to create a bunch of text files in a single directory on a 
> Linux system,
> something like this.
> 
> import os
> 
> routers = ['adnc-6321', 'adnp-2341', 'adnw-2632']
> 
> for i in routers:
>     os.system('/bin/touch' %s) % i

I think you're close, just a little out of order. Think about it this way:
- first you need to create a string containing the command, using the 
string formatting operations.
'/bin/touch %s' % i
will do that. Note the %s is part of the string, and the % i is part of 
the formatting expression.

- next you pass the formatted string to os.system(). So the whole 
formatting expression has to go inside the parentheses - the value of 
the expression is passed to os.system():
os.system('/bin/touch %s' % i)

You could also do this without calling out to the system - just open a 
file for writing and close it again:
open(i, 'w').close()

Kent



More information about the Tutor mailing list