如何在python中扩展名为.txt
的目录中找到所有文件?
#1楼
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
#2楼
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
#3楼
此代码使我的生活更简单。
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)
#4楼
import os
path = 'mypath/path'
files = os.listdir(path)
files_txt = [i for i in files if i.endswith('.txt')]
#5楼
带有子目录的功能解决方案:
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"))))
#6楼
使用fnmatch: https : //docs.python.org/2/library/fnmatch.html
import fnmatch
import os
for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.txt'):
print file
#7楼
试试这个,这将递归地找到所有文件:
import glob, os
os.chdir("H:\\wallpaper")# use whatever you directory
#double\\ no single \
for file in glob.glob("**/*.psd", recursive = True):#your format
print(file)
#8楼
使用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
#9楼
Python具有执行此操作的所有工具:
import os
the_dir = 'the_dir_that_want_to_search_in'
all_txt_files = filter(lambda x: x.endswith('.txt'), os.listdir(the_dir))
#10楼
使用glob 。
>>> import glob
>>> glob.glob('./*.txt')
['./outline.txt', './pip-log.txt', './test.txt', './testingvim.txt']
#11楼
这样的事情应该做的
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.txt'):
print file
#12楼
您可以使用glob
:
import glob, os
os.chdir("/mydir")
for file in glob.glob(