简体   繁体   中英

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 ?

find . -maxdepth 1 -name "*.py" -exec  python3 {} \;
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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM