【问题标题】:Calling a function on every .py file that is not empty in every folder and subfolder in python在python中的每个文件夹和子文件夹中对每个非空的.py文件调用一个函数
【发布时间】:2021-09-03 00:52:11
【问题描述】:

我需要在每个文件夹和子文件夹中不为空的每个 .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 中的子目录只列出一个子目录。 我在 stackoverflow 上找到了很多关于如何做到这一点的建议,但似乎没有什么对我有用。根目录为“C:/Users/MuellerM/PycharmProjects/Projects”。

【问题讨论】:

  • 我不明白你的问题是什么。如果你想在每个文件上运行handledisclaimer,那么也许你应该将它作为参数发送handledisclaimer(fname)
  • 你错了for-loops。您应该分别运行 for subdirectory in dirs: ...for filename in files: ... ,而不是 in dirs
  • 可能首先使用print() 来查看执行了代码的哪一部分以及变量中有什么。它被称为"print debuging"。此时您在for-loops 中使用了错误的变量。它必须是 ... in file 而不是 ...in dirs

标签: python function recursion directory subdirectory


【解决方案1】:

我无法在您的文件上对其进行测试,但您以错误的方式使用 for-loop,并且您使用了错误的变量 导入操作系统

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")

【讨论】:

  • 非常感谢,这解决了我的问题:)
猜你喜欢
  • 2019-06-12
  • 1970-01-01
  • 2013-08-25
  • 1970-01-01
  • 1970-01-01
  • 2021-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多