对 python 中每个文件夹和子文件夹中非空的每个 .py 文件调用一个函数
Calling a function on every .py file that is not empty in every folder and subfolder in python
我需要对每个文件夹和子文件夹中不为空的每个 .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 中的子目录只列出了一个子目录。
我在 Whosebug 上找到了很多关于如何做到这一点的建议,但似乎对我没有任何帮助。根目录是“C:/Users/MuellerM/PycharmProjects/Projects”.
我无法在你的文件上测试它,但你以错误的方式使用了 for
-循环,并且你使用了错误的变量
导入 os
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")
我需要对每个文件夹和子文件夹中不为空的每个 .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 中的子目录只列出了一个子目录。 我在 Whosebug 上找到了很多关于如何做到这一点的建议,但似乎对我没有任何帮助。根目录是“C:/Users/MuellerM/PycharmProjects/Projects”.
我无法在你的文件上测试它,但你以错误的方式使用了 for
-循环,并且你使用了错误的变量
导入 os
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")