I tired this:
import os
for file in os.listdir("D:\\Python\\Projects\\p1"):
if file.endswith(".py"):
print(os.path.join("/Python files:", file))
but this only gives me the files in one folder but I want all py files of all folders example: p1 has sub folders which have some py files and those sub folder which have some py files and so on "p1-->sub_folder-->sub_folder--->sub_folder" so, my need is to get all the py files in all the folders and sub folders.
Any help/suggestion will help me alot thanks
CodePudding user response:
You can use the rglob function:
from pathlib import Path
for one_file in Path("D:\\Python\\Projects\\p1").rglob("*.py"):
print(one_file)
Edit:
If you need to avoid a subfolder, you can do something like this:
from pathlib import Path
for one_file in Path("D:\\Python\\Projects\\p1").rglob("*.py"):
if "venv" not in one_file.parts:
print(one_file)
CodePudding user response:
You can also use this:
import os
for path, subdirs, files in os.walk("path\"):
for name in files:
if name.endswith(".py"):
print(os.path.join(path, name))