Executing all files inside a folder in Python
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 ?
4 Answers
4
find . -maxdepth 1 -name "*.py" -exec python3 {} ;
Added
maxdepth 1
– RedEyed
Jun 29 at 11:28
maxdepth 1
use python instead python3 for less than Python 2.7
– Praveen Reddy
16 hours ago
@RedEyed: Thanks so much
– Praveen Reddy
16 hours ago
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.
/bin/ls
Use a loop inside the folder:
#!/bin/bash
for script in $(ls); do
python $script
done
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
It's not a single command
– RedEyed
Jun 29 at 10:46
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
This will eventually recurse in subdirectories, which might not be what the OP wants.
– bruno desthuilliers
Jun 29 at 11:23