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)
from path import path
p = path('/path/to/the/directory')
for f in p.files(pattern='*.txt'):
print f
117
这段代码让我的生活更简单 .
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)
11
要从同一目录中名为“data”的文件夹中获取“.txt”文件名数组,我通常使用以下简单的代码行:
import os
fileNames = [fileName for fileName in os.listdir("data") if fileName.endswith(".txt")]
2
import glob
import os
path=os.getcwd()
extensions=('*.py','*.cpp')
for i in extensions:
for files in glob.glob(i):
print files
2
将'dataPath'文件夹中的所有'.txt'文件名称作为Pythonic方式的列表
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
3
一个类似于ghostdog的可复制的解决方案:
def get_all_filepaths(root_path, ext):
"""
Search all files which have a given extension within root_path.
This ignores the case of the extension and searches subdirectories, too.
Parameters
----------
root_path : str
ext : str
Returns
-------
list of str
Examples
--------
>>> get_all_filepaths('/run', '.lock')
['/run/unattended-upgrades.lock',
'/run/mlocate.daily.lock',
'/run/xtables.lock',
'/run/mysqld/mysqld.sock.lock',
'/run/postgresql/.s.PGSQL.5432.lock',
'/run/network/.ifstate.lock',
'/run/lock/asound.state.lock']
"""
import os
all_files = []
for root, dirs, files in os.walk(root_path):
for filename in files:
if filename.lower().endswith(ext):
all_files.append(os.path.join(root, filename))
return all_files
25
这里有更多相同版本会产生稍微不同的结果:
glob.iglob()
import glob
for f in glob.iglob("/mydir/*/*.txt"): # generator, search immediate subdirectories
print f
>>> import os
>>> path = '/usr/share/cups/charmaps'
>>> text_files = [f for f in os.listdir(path) if f.endswith('.txt')]
>>> text_files
['euc-cn.txt', 'euc-jp.txt', 'euc-kr.txt', 'euc-tw.txt', ... 'windows-950.txt']
26
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
import os
for root, dirs, files in os.walk("/mydir"):
for file in files:
if file.endswith(".txt"):
print(os.path.join(root, file))
2
这是 extend() 的一个
types = ('*.jpg', '*.png')
images_list = []
for files in types:
images_list.extend(glob.glob(os.path.join(path, files)))
190
许多用户回复了 os.walk 答案,其中包括所有文件以及所有目录和子目录及其文件 .
import os
def files_in_dir(path, extension=''):
"""
Generator: yields all of the files in <path> ending with
<extension>
\param path Absolute or relative path to inspect,
\param extension [optional] Only yield files matching this,
\yield [filenames]
"""
for _, dirs, files in os.walk(path):
dirs[:] = [] # do not recurse directories.
yield from [f for f in files if f.endswith(extension)]
# Example: print all the .py files in './python'
for filename in files_in_dir('./python', '*.py'):
print("-", filename)
或者对于不需要发电机的一次性:
path, ext = "./python", ext = ".py"
for _, _, dirfiles in os.walk(path):
matches = (f for f in dirfiles if f.endswith(ext))
break
for filename in matches:
print("-", filename)
如果您要将匹配用于其他内容,您可能希望将其设置为列表而不是生成器表达式:
matches = [f for f in dirfiles if f.endswith(ext)]
18
您可以尝试此代码
import glob
import os
filenames_without_extension = [os.path.basename(c).split('.')[0:1][0] for c in glob.glob('your/files/dir/*.txt')]
filenames_with_extension = [os.path.basename(c) for c in glob.glob('your/files/dir/*.txt')]
3
如果文件夹包含大量文件或内存是约束,请考虑使用生成器:
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')]
import os
def findFilesInFolder(path, pathList, extension, subFolders = True):
""" Recursive function to find all files of an extension type in a folder (and optionally in all subfolders too)
path: Base directory to find files
pathList: A list that stores all paths
extension: File extension to find
subFolders: Bool. If True, find files in all subfolders under path. If False, only searches files in the specified folder
"""
try: # Trapping a OSError: File permissions problem I believe
for entry in os.scandir(path):
if entry.is_file() and entry.path.endswith(extension):
pathList.append(entry.path)
elif entry.is_dir() and subFolders: # if its a directory, then repeat process as a nested function
pathList = findFilesInFolder(entry.path, pathList, extension, subFolders)
except OSError:
print('Cannot access ' + path +'. Probably a permissions error')
return pathList
dir_name = r'J:\myDirectory'
extension = ".txt"
pathList = []
pathList = findFilesInFolder(dir_name, pathList, extension, True)
import os
dir = ["e","x","e"]
p = os.listdir('E:') #path
for n in range(len(p)):
name = p[n]
myfile = [name[-3],name[-2],name[-1]] #for .txt
if myfile == dir :
print(name)
else:
print("nops")
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
93
你可以试试这段代码:
import glob
import os
os.chdir("D:\...\DirName")
filename_arr={}
i=0
for files in glob.glob("*.txt"):
filename_arr[i] = files
i= i+1
for key,value in filename_arr.items():
print key , value
import os, os.path
for root, dirs, files in os.walk(dir):
for f in files:
fullpath = os.path.join(root, f)
if os.path.splitext(fullpath)[1] == '.txt':
print fullpath
或者使用发电机:
import os, os.path
fileiter = (os.path.join(root, f)
for root, _, files in os.walk(dir)
for f in files)
txtfileiter = (f for f in fileiter if os.path.splitext(f)[1] == '.txt')
for txt in txtfileiter:
print txt
5
import glob,os
data_dir = 'data_folder/'
file_dir_extension = os.path.join(data_dir, '*.txt')
for file_name in glob.glob(file_dir_extension):
if file_name.endswith('.txt'):
print file_name
为了我 . 这很经典 .
6
具有子目录的功能解决方案:
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"))))
30 回答
试试这个会在文件夹或文件夹中找到你的所有文件
path.py是另一种选择:https://github.com/jaraco/path.py
这段代码让我的生活更简单 .
要从同一目录中名为“data”的文件夹中获取“.txt”文件名数组,我通常使用以下简单的代码行:
将'dataPath'文件夹中的所有'.txt'文件名称作为Pythonic方式的列表
一个类似于ghostdog的可复制的解决方案:
这里有更多相同版本会产生稍微不同的结果:
glob.iglob()
glob.glob1()
fnmatch.filter()
Python有所有工具可以做到这一点:
这样的东西会起作用:
我建议你使用fnmatch和上面的方法 . 通过这种方式,您可以找到以下任何一项:
姓名 . txt ;
姓名 . TXT ;
姓名 . Txt
.
你可以使用glob:
或者只是os.listdir:
或者如果要遍历目录,请使用os.walk:
这是
extend()
的一个许多用户回复了
os.walk
答案,其中包括所有文件以及所有目录和子目录及其文件 .或者对于不需要发电机的一次性:
如果您要将匹配用于其他内容,您可能希望将其设置为列表而不是生成器表达式:
您可以尝试此代码
如果文件夹包含大量文件或内存是约束,请考虑使用生成器:
选项A:迭代
选项B:全部获取
Python v3.5
在递归函数中使用os.scandir的快速方法 . 在文件夹和子文件夹中搜索具有指定扩展名的所有文件 .
你可以简单地使用pathlib s glob 1:
或循环:
如果你想要它递归你可以使用
.glob('**/*.txt)
1
pathlib
模块包含在python 3.4的标准库中 . 但是,即使在较旧的Python版本上(即使用conda
或pip
),您也可以安装该模块的后端端口:pathlib和pathlib2 .这样的事情应该可以胜任
使用glob .
我做了一个测试(Python 3.6.4,W7x64),看看哪个解决方案对于一个文件夹,没有子目录来说是最快的,以获取具有特定扩展名的文件的完整文件路径列表 .
为了缩短它,对于这个任务来说,
os.listdir()
是最快的,并且速度是次佳的1.7倍:os.walk()
(有休息!),2.7倍于pathlib
,比os.scandir()
快3.2倍,比glob
快3.3倍 .请记住,当您需要递归结果时,这些结果会发生变化 . 如果你复制/粘贴下面的一个方法,请添加.lower(),否则在搜索.ext时找不到.EXT .
结果:
使用
for
循环的简单方法:虽然这可以更加通用化 .
使用Python OS模块查找具有特定扩展名的文件 .
这里有一个简单的例子:
你可以试试这段代码:
使用fnmatch:https://docs.python.org/2/library/fnmatch.html
我喜欢os.walk():
或者使用发电机:
为了我 . 这很经典 .
具有子目录的功能解决方案: