Home > Enterprise >  How to run file in subfolder
How to run file in subfolder

Time:01-10

import os

root_dir = "D:\extention"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".py"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
                dir_path=(f"Path: ", os.path.join(folder, f))

with this code i can find py file in subfolder but cant run the file

I try to use os.system but get error.

I have very little knowledge of python can anyone help me.

CodePudding user response:

Your dir_path is a tuple not a string. Leave out the round brackets.

import os

root_dir = "D:\extention"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".py"):
                print(f"File Name: {f}")
                dir_path=os.path.join(folder, f)
                print(f"Path: {dir_path}")
                os.system(dir_path)

CodePudding user response:

This will execute the .py file specified by dir_path:

import subprocess

subprocess.run(["python", dir_path])

If you need to capture the output, you could use this:

import subprocess

process = subprocess.Popen(["python", dir_path], stdout=subprocess.PIPE)
output, error = process.communicate()
print(output)

You only need to integrate one of the alternatives to your code, like this:

import os
import subprocess

root_dir = "D:\extention"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".py"):
                print("File Name: ", f)
                dir_path = os.path.join(folder, f)
                print("Path: ", dir_path)
                subprocess.run(["python", dir_path])

  • Related