How to get files in a directory, including all subdirectories

前端 未结 6 1479
耶瑟儿~
耶瑟儿~ 2020-12-04 12:45

I\'m trying to get a list of all log files (.log) in directory, including all subdirectories.

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 13:24

    I have a solution:

    import os
    for logfile in os.popen('find . -type f -name *.log').read().split('\n')[0:-1]:
          print logfile
    

    or

    import subprocess
    (out, err) = subprocess.Popen(["find", ".", "-type", "f", "-name", "*.log"], stdout=subprocess.PIPE).communicate()
    for logfile in out.split('\n')[0:-1]:
      print logfile
    

    These two take the advantage of find . -type f -name *.log.

    The first one is simpler but not guaranteed for white-space when add -name *.log, but worked fine for simply find ../testdata -type f (in my OS X environment).

    The second one using subprocess seems more complicated, but this is the white-space safe one (again, in my OS X environment).

    This is inspired by Chris Bunch, in the answer https://stackoverflow.com/a/3503909/2834102

提交回复
热议问题