logo

Python의 os.walk()

Python에서 파일 시스템을 탐색하는 방법은 무엇입니까? 시스템에 아래 파일 구조가 지정되어 있고 모든 분기를 위에서 아래로 완전히 탐색하고 싶다고 가정해 보겠습니다. 예시 파일 시스템

둥근 수학 자바

os.walk()는 파이썬에서 어떻게 작동하나요?

OS.walk()는 하향식 또는 상향식으로 트리를 탐색하여 디렉토리 트리에 파일 이름을 생성합니다. 디렉터리 최상위(top 자체 포함)에 루트가 있는 트리의 각 디렉터리에 대해 3-튜플(dirpath, dirnames, filenames)이 생성됩니다.



  • 루트 : 지정한 디렉토리에서만 디렉토리를 인쇄합니다.
  • 말하다: 루트에서 하위 디렉터리를 인쇄합니다.
  • 파일: 루트 및 디렉터리의 모든 파일을 인쇄합니다.
파이썬3
# Driver function import os if __name__ == "__main__": for (root,dirs,files) in os.walk('.', topdown=True): print (root) print (dirs) print (files) print ('--------------------------------')>

산출:

클래스 대 객체 자바
['gfg-article-deep-crawl-master (1)', '.ipynb_checkpoints'] ['t.pdf', 'Untitled.ipynb'] -------------------------------- ./gfg-article-deep-crawl-master (1) ['gfg-article-deep-crawl-master'] [] -------------------------------- ./gfg-article-deep-crawl-master (1)/gfg-article-deep-crawl-master ['check_rank'] ['rank_scraper.py', 'search-page (copy).html', '.gitignore', 'search-page.html', 'globals.py', 'requirements.txt', 'sel_scraper.py', 'README.md'] -------------------------------- ./gfg-article-deep-crawl-master (1)/gfg-article-deep-crawl-master/check_rank [] ['selenium.py', 'tools.py', '__init__.py', 'run_check.py'] -------------------------------- ./.ipynb_checkpoints [] ['Untitled-checkpoint.ipynb'] -------------------------------->

Os.Walk를 사용한 중첩 목록 이해

디렉토리 트리에서 Python 파일을 찾는 프로그램은 .py 확장자로 끝나는 파일을 찾아야 함을 의미합니다.

파이썬
# code import os if __name__ == '__main__': pythonFiles = [file for dirs in os.walk('.', topdown=True) for file in dirs[2] if file.endswith('.py')] print('python files in the directory tree are ') for r in pythonFiles: print(r)>

산출
python files in the directory tree are Solution.py>