Running all python codes saved in a folder from Jupyter Notebook

Question:

Is there any python code I can use to automatically detect all ipynb files saved inside a specific folder and run them sequentially?

I can identify them all using this function:

path = glob.iglob(f"/Users/[…]")

But unfortunately I cannot run them using

for file in path
%run file

Any help would be really appreciated!

Asked By: Cla Rosie

||

Answers:

import os
import subprocess

# Get a list of files in the directory
files = os.listdir('Yourdirectory')

py_files = [f for f in files if f.endswith('.py')]

py_files.sort()

for file in py_files:
    subprocess.run(['python', file])
Answered By: Elkhan
import os

# specify the directory where the ipynb files are stored
directory = '/Users/[directory]'

# loop through all files in the directory
for filename in os.listdir(directory):
    # check if the file is an ipynb notebook
    if filename.endswith('.ipynb'):
        # build the command to run the notebook using the %run magic command
        command = f'%run "{os.path.join(directory, filename)}"'
        # execute the command
        %run -i $command
Answered By: leoodz
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.