1

I want to execute several .py files that have similar names. The goal is call on a1.py, a2.py, and a3.py. I've tried what is below, but I can't get it to work. How do I insert each element in "n" into the filename to execute several scripts? Thanks for any help.

n = [1,2,3]

for x in n:
     execfile('C:/a$n.py')
levi
  • 22,001
  • 7
  • 73
  • 74
Matt
  • 13
  • 4
  • possible duplicate of [Python string formatting: % vs. .format](http://stackoverflow.com/questions/5082452/python-string-formatting-vs-format) – Darrick Herwehe Feb 13 '15 at 00:35

3 Answers3

1

Personally, I really prefer using string formatting to concatenation (more robust to various datatypes). Also, there's no reason to keep a list like that around, and it can be replace by range

for x in range(1,4): 
    execfile('C:/a%s.py' % x)

range(1, 4) == [1, 2, 3]  # True

That said, the format command used by Marcin is technically more pythonic. I personally find it overly verbose though.

I believe that string concatenation is the most performant option, but performance really shouldn't be the deciding factor for you here.

To recap:

Pythonic Solution:

execfile('C:/a{}.py'.format(x))

C-type Solution (that I personally prefer):

execfile('C:/a%s.py' % x)

Performant Solution (Again, performance really shouldn't be your driving force here)

execfile('C:/a' + str(x) + '.py')

EDIT: Turns out I was wrong and the C-type solution is most performant. timeit results below:

$ python -m timeit '["C:/a{}.py".format(x) for x in range(1,4)]'
100000 loops, best of 3: 4.58 usec per loop

$ python -m timeit '["C:/a%s.py" % x for x in range(1,4)]'
100000 loops, best of 3: 2.92 usec per loop

$ python -m timeit '["C:/a" + str(x) + ".py" for x in range(1,4)]'
100000 loops, best of 3: 3.32 usec per loop
Slater Victoroff
  • 21,376
  • 21
  • 85
  • 144
0
for x in n: 
   execfile('C:/a{}.py'.format(x))

Better:

for x in range(1,4):
    execfile('C:/a{}.py'.format(x))
levi
  • 22,001
  • 7
  • 73
  • 74
0

You can do this:

n = [1,2,3]

for x in n: 
    execfile('C:/a{}.py'.format(x))
    print('C:/a{}.py'.format(x))

The names will be:

C:/a1.py
C:/a2.py
C:/a3.py
Marcin
  • 215,873
  • 14
  • 235
  • 294