Find all files in a directory with extension .txt

2018-12-31 03:14发布

How can I find all the files in a directory having the extension .txt in python?

30条回答
君临天下
2楼-- · 2018-12-31 03:23
import glob
import os

path=os.getcwd()

extensions=('*.py','*.cpp')

for i in extensions:
  for files in glob.glob(i):
     print files
查看更多
君临天下
3楼-- · 2018-12-31 03:23

Here's one with extend()

types = ('*.jpg', '*.png')
images_list = []
for files in types:
    images_list.extend(glob.glob(os.path.join(path, files)))
查看更多
零度萤火
4楼-- · 2018-12-31 03:24

You can simply use pathlibs glob 1:

import pathlib

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

or in a loop:

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

If you want it recursive you can use .glob('**/*.txt)


1The pathlib module was included in the standard library in python 3.4. But you can install back-ports of that module even on older Python versions (i.e. using conda or pip): pathlib and pathlib2.

查看更多
浪荡孟婆
5楼-- · 2018-12-31 03:24

To get an array of ".txt" file names from a folder called "data" in the same directory I usually use this simple line of code:

import os
fileNames = [fileName for fileName in os.listdir("data") if fileName.endswith(".txt")]
查看更多
后来的你喜欢了谁
6楼-- · 2018-12-31 03:26

Something like that should do the job

for root, dirs, files in os.walk(directory):
    for file in files:
        if file.endswith('.txt'):
            print file
查看更多
骚的不知所云
7楼-- · 2018-12-31 03:26

Functional solution with sub-directories:

from fnmatch import filter
from functools import partial
from itertools import chain
from os import path, walk

print(*chain(*(map(partial(path.join, root), filter(filenames, "*.txt")) for root, _, filenames in walk("mydir"))))
查看更多
登录 后发表回答