>  기사  >  백엔드 개발  >  디렉터리에서 모든 .txt 파일을 찾는 방법

디렉터리에서 모든 .txt 파일을 찾는 방법

anonymity
anonymity원래의
2019-05-25 09:32:495240검색

利用python找到指定路径下的全部txt文件。

디렉터리에서 모든 .txt 파일을 찾는 방법

指定路径中可能又包含文件夹,这一层的文件夹里可能也包含txt文件或者其他文件夹,其他文件夹又包含......等这样循环下去。当然,如果需要的不是txt文件,在代码中只要修改一点点,就可以找到自己想要的文件了。

import os
root = "H:\\ab123"
def findtxt(path, ret):
    """Finding the *.txt file in specify path"""
    filelist = os.listdir(path)
    for filename in filelist:
        de_path = os.path.join(path, filename)
        if os.path.isfile(de_path):
            if de_path.endswith(".txt"): #Specify to find the txt file.
                ret.append(de_path)
        else:
            findtxt(de_path, ret)
 
ret = []
findtxt(root, ret)
for path in ret:
    print(path)

위 내용은 디렉터리에서 모든 .txt 파일을 찾는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.