Execute the Python File within the Folder

Question:

I’m trying to open a .py file to execute within a folder

I tried to open text file and it did work when I’m trying to open a .py file it didn’t work

import os
os.popen("myfolder\run.txt")

it works but when I try to below code to run a .py file like

import os
os.popen("myfolder\run.py")

it didn’t work

Asked By: Mac

||

Answers:

If your trying to execute the python file that’s in a folder, you need to switch your directory to that folder.

To do that, do:

os.chdir('myfolder')

Next, to execute the .py file, do:

os.system('python run.py')

Altogether, this code should work:

import os
os.chdir('myfolder')
os.system('python run.py')

This code should run the run.py file.

Answered By: donut28
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.