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!
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])
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
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!
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])
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