pythonlistfor-loopexecfile

How do I reference several scripts with similar names in Python with a "for" statement?


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')

Solution

  • 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