Mac
Mac

Reputation: 23

Execute the Python File within the Folder

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

Upvotes: 2

Views: 64

Answers (1)

donut28
donut28

Reputation: 55

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.

Upvotes: 1

Related Questions