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:33
import os

path = 'mypath/path' 
files = os.listdir(path)

files_txt = [i for i in files if i.endswith('.txt')]
查看更多
与君花间醉酒
3楼-- · 2018-12-31 03:33

I suggest you to use fnmatch and the upper method. In this way you can find any of the following:

  1. Name.txt;
  2. Name.TXT;
  3. Name.Txt

.

import fnmatch
import os

    for file in os.listdir("/Users/Johnny/Desktop/MyTXTfolder"):
        if fnmatch.fnmatch(file.upper(), '*.TXT'):
            print(file)
查看更多
十年一品温如言
4楼-- · 2018-12-31 03:34

path.py is another alternative: 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
查看更多
泪湿衣
5楼-- · 2018-12-31 03:35

This code makes my life simpler.

import os
fnames = ([file for root, dirs, files in os.walk(dir)
    for file in files
    if file.endswith('.txt') #or file.endswith('.png') or file.endswith('.pdf')
    ])
for fname in fnames: print(fname)
查看更多
墨雨无痕
6楼-- · 2018-12-31 03:35

To get all '.txt' file names inside 'dataPath' folder as a list in a Pythonic way

from os import listdir
from os.path import isfile, join
path = "/dataPath/"
onlyTxtFiles = [f for f in listdir(path) if isfile(join(path, f)) and  f.endswith(".txt")]
print onlyTxtFiles
查看更多
骚的不知所云
7楼-- · 2018-12-31 03:36
import os
import sys 

if len(sys.argv)==2:
    print('no params')
    sys.exit(1)

dir = sys.argv[1]
mask= sys.argv[2]

files = os.listdir(dir); 

res = filter(lambda x: x.endswith(mask), files); 

print res
查看更多
登录 后发表回答