learningstudent
learningstudent

Reputation: 577

Executing all files inside a folder in Python

I have 20 Python files which is stored inside a directory in ubuntu 14.04 like 1.py, 2.py, 3.py , 4.py soon

i have execute these files by "python 1.py", "python 2.py" soon for 20 times.

is their a way to execute all python files inside a folder by single command ?

Upvotes: 2

Views: 108

Answers (4)

RedEyed
RedEyed

Reputation: 2135

find . -maxdepth 1 -name "*.py" -exec  python3 {} \;

Upvotes: 2

Duarte Arribas
Duarte Arribas

Reputation: 317

You can try with the library glob.

First install the glob lybrary.

Then import it:

import glob

Then use a for loop to iterate through all files:

for fileName in glob.glob('*.py'):
    #do something, for example var1 = filename

The * is used to open them all.

More information here: https://docs.python.org/2/library/glob.html

Upvotes: 0

Nic3500
Nic3500

Reputation: 8601

for F in $(/bin/ls *.py); do ./$F; done

You can use any bash construct directly from the command line, like this for loop. I also force /bin/ls to make sure to bypass any alias you might have set.

Upvotes: 1

Netwave
Netwave

Reputation: 42678

Use a loop inside the folder:

#!/bin/bash
for script in $(ls); do
    python $script
done

Upvotes: 0

Related Questions