如何在python中找到扩展名为.txt的目录中的所有文件?


当前回答

使用Python OS模块查找具有特定扩展名的文件。

简单的例子如下:

import os

# This is the path where you want to search
path = r'd:'  

# this is extension you want to detect
extension = '.txt'   # this can be : .jpg  .png  .xls  .log .....

for root, dirs_list, files_list in os.walk(path):
    for file_name in files_list:
        if os.path.splitext(file_name)[-1] == extension:
            file_name_path = os.path.join(root, file_name)
            print file_name
            print file_name_path   # This is the full path of the filter file

其他回答

用一团。

>>> import glob
>>> glob.glob('./*.txt')
['./outline.txt', './pip-log.txt', './test.txt', './testingvim.txt']

如果文件夹包含大量文件或内存受限,可以考虑使用生成器:

def yield_files_with_extensions(folder_path, file_extension):
   for _, _, files in os.walk(folder_path):
       for file in files:
           if file.endswith(file_extension):
               yield file

选项A:迭代

for f in yield_files_with_extensions('.', '.txt'): 
    print(f)

选项B:全部获取

files = [f for f in yield_files_with_extensions('.', '.txt')]

Path.py是另一种选择:https://github.com/jaraco/path.py

from path import path
p = path('/path/to/the/directory')
for f in p.files(pattern='*.txt'):
    print f

这样的东西就可以了

for root, dirs, files in os.walk(directory):
    for file in files:
        if file.endswith('.txt'):
            print(file)

你可以简单地使用pathlibs glob 1:

import pathlib

list(pathlib.Path('your_directory').glob('*.txt'))

或在循环中:

for txt_file in pathlib.Path('your_directory').glob('*.txt'):
    # do something with "txt_file"

如果你想递归你可以使用。glob('**/*.txt')


1 pathlib模块被包含在python 3.4的标准库中。但是你甚至可以在旧的Python版本(即使用conda或pip)上安装该模块的反向端口:pathlib和pathlib2。