如何解决在python的每个文件夹和子文件夹中的每个.py文件上调用一个函数
我需要在每个文件夹和子文件夹中不为空的每个 .py 文件上调用函数“handledisclaimer()”。有时只有一个子文件夹,有时有两三个,例如。
Projects
->jenkins
.jenkinsfile
->tests
->A
->A.a
init.py
test.py
->A.aa
init.py
Results.tar
test.py
->B
->B.b
->B.b.1
init.py
test.py
->B.b.2
init.py
test.py
init.py
conftest.py
init.py
helpers.py
还有更多文件夹,但我当然不会列出所有人。 我已经尝试过类似这样的事情。
def navigate_through_directory():
for dirpath,dirs,files in os.walk("C:/Users/MuellerM/PycharmProjects/Projects"):
for subdirectory in dirs:
for filename in dirs:
fname = os.path.join(dirpath,filename)
if fname.endswith(".py") and os.stat(fname).st_size >0:
handle_disclaimer()
continue
else:
continue
然而,dirs 中的 subdirectory 只是列出了一个子目录。 我在 stackoverflow 上找到了很多关于如何做到这一点的建议,但似乎对我没有任何作用。根目录是“C:/Users/MuellerM/PycharmProjects/Projects”。
解决方法
我无法在您的文件上测试它,但是您以错误的方式使用了 for
循环,并且您使用了错误的变量
导入操作系统
def navigate_through_directory(directory):
for root,dirs,files in os.walk(directory):
print('[DEBUG] root:',root)
# - work with dirnames -
for dirname in dirs:
fullpath = os.path.join(root,dirname)
print('[DEBUG] dir:',fullpath)
# - work with filenames -
for filename in files: # <-- files,not dirs
fullpath = os.path.join(root,filename)
print('[DEBUG] file:',fullpath)
if fullpath.endswith(".py") and os.stat(fullpath).st_size > 0:
handle_disclaimer(fullpath)
#navigate_through_directory("C:/Users/MuellerM/PycharmProjects/Projects")
navigate_through_directory("/home/furas/test")
,
如果你使用的是python3.5或以上可以试试
import glob
root_dir = '/'
# path of root needs to be absolute of your directory
for filename in glob.iglob(root_dir + '**/*.py',recursive=True):
print(filename) # Here you got the file name can execute instruction according to your wish
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。