ChatGPT解决这个技术问题 Extra ChatGPT

在 Python 中查找扩展名为 .txt 的目录中的所有文件

这个问题的答案是社区的努力。编辑现有答案以改进这篇文章。它目前不接受新的答案或交互。

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


M
Ma0

您可以使用 glob

import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
    print(file)

或者干脆os.listdir

import os
for file in os.listdir("/mydir"):
    if file.endswith(".txt"):
        print(os.path.join("/mydir", file))

或者如果您想遍历目录,请使用 os.walk

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,您将如何使用该信息创建文件或列表?
@ghostdog74:在我看来,写 for file in f 比写 for files in f 更合适,因为变量中的内容是单个文件名。更好的做法是将 f 更改为 files,然后 for 循环可以变为 for file in files
@computermacgyver:不,file 不是保留字,只是预定义函数的名称,因此很有可能在您自己的代码中将其用作变量名。虽然确实应该避免这样的冲突,但 file 是一种特殊情况,因为几乎不需要使用它,因此它通常被视为准则的例外。如果您不想这样做,PEP8 建议在此类名称后附加一个下划线,即 file_,您必须同意它仍然非常易读。
谢谢,马蒂诺,你是绝对正确的。我太快下结论了。
#2 的一种更 Pythonic 的方式可以是 [f for f in os.listdir('/mydir') if f.endswith('.txt')] 中的文件:
M
Muhammad Alkarouri

使用 glob

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

这不仅简单,而且不区分大小写。 (至少,它应该在 Windows 上。我不确定其他操作系统。)
请注意,如果您的 python 低于 3.5,glob 将无法递归找到文件。 more inform
最好的部分是你可以使用正则表达式 test*.txt
@JonCoombs 不。至少不是在 Linux 上。
这只会在当前顶级目录中查找文件,而不是在整个目录中。
g
greybeard

像这样的东西应该可以完成这项工作

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

+1 用于将变量命名为 root, dirs, files 而不是 r, d, f。更具可读性。
请注意,这是区分大小写的(与 .TXT 或 .Txt 不匹配),因此您可能希望使用 if file.lower().endswith('.txt'):
您的答案涉及子目录。
作为列表理解:text_file_list = [file for root, dirs, files in os.walk(folder) for file in files if file.endswith('.txt')]
S
Seth

像这样的东西会起作用:

>>> 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']

我将如何保存到 text_files 的路径? ['path/euc-cn.txt', ...'path/windows-950.txt']
您可以对 text_files 的每个元素使用 os.path.join。它可能类似于 text_files = [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.txt')]
J
Jeril

您可以简单地使用 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')

1pathlib 模块包含在 python 3.4 的标准库中。但您甚至可以在较旧的 Python 版本(即使用 condapip)上安装该模块的后端端口:pathlibpathlib2


旧的 python 版本不支持 **/*.txt。所以我解决了这个问题:foundfiles= subprocess.check_output("ls **/*.txt", shell=True) for foundfile in foundfiles.splitlines(): print foundfile
@Roman 是的,这只是展示 pathlib 可以做什么,我已经包含了 Python 版本要求。 :) 但是,如果您的方法尚未发布,为什么不将其添加为另一个答案?
是的,发布答案肯定会给我更好的格式化可能性。我把它贴在 there 上,因为我认为这是一个更适合它的地方。
请注意,如果您想递归查找项目,也可以使用 rglob。例如.rglob('*.txt')
u
user3281344
import os

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

files_txt = [i for i in files if i.endswith('.txt')]

T
TamaMcGlinn

我喜欢os.walk()

import os

for root, dirs, files in os.walk(dir):
    for f in files:
        if os.path.splitext(f)[1] == '.txt':
            fullpath = os.path.join(root, f)
            print(fullpath)

或使用发电机:

import os

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)

这是提供完整路径和递归功能的唯一答案。
j
jfs

以下是相同版本的更多版本,它们会产生略有不同的结果:

glob.iglob()

import glob
for f in glob.iglob("/mydir/*/*.txt"): # generator, search immediate subdirectories 
    print f

glob.glob1()

print glob.glob1("/mydir", "*.tx?")  # literal_directory, basename_pattern

fnmatch.filter()

import fnmatch, os
print fnmatch.filter(os.listdir("/mydir"), "*.tx?") # include dot-files

出于好奇,glob1()glob 模块中的一个辅助函数,它没有在 Python 文档中列出。有一些内联注释描述了它在源文件中的作用,请参阅 .../Lib/glob.py
@martineau:glob.glob1() 不公开,但在 Python 2.4-2.7;3.0-3.2; 上可用pypy; jython github.com/zed/test_glob1
谢谢,在决定是否在模块中使用未记录的私有函数时,这是很好的附加信息。 ;-) 这里还有一点。 Python 2.7 版本只有 12 行长,看起来很容易从 glob 模块中提取出来。
p
pyDdev

试试这个,这将递归地找到你所有的文件:

import glob, os
os.chdir("H:\\wallpaper")# use whatever directory you want

#double\\ no single \

for file in glob.glob("**/*.txt", recursive = True):
    print(file)

不是递归版本(双星:**)。仅在 python 3 中可用。我不喜欢的是 chdir 部分。没必要。
好吧,您可以使用 os 库来加入路径,例如 filepath = os.path.join('wallpaper'),然后将其用作 glob.glob(filepath+"**/*.psd", recursive = True),这将产生相同的结果。
请注意,应将 file 分配重命名为 _file 之类的名称,以免与保存的类型名称冲突
我注意到它不区分大小写(至少在 Windows 上)。如何使模式匹配区分大小写?
glob 在 ipython 中的行为与在运行代码中的行为不同,并且通常令人惊讶。过去我告诉自己要放弃它并继续固执,回到它,并为此付出代价。
D
DougR

Python v3.5+

在递归函数中使用 os.scandir 的快速方法。在文件夹和子文件夹中搜索具有指定扩展名的所有文件。即使查找 10,000 个文件,它也很快。

我还包含一个将输出转换为 Pandas Dataframe 的函数。

import os
import re
import pandas as pd
import numpy as np


def findFilesInFolderYield(path,  extension, containsTxt='', subFolders = True, excludeText = ''):
    """  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
    extension:          File extension to find.  e.g. 'txt'.  Regular expression. Or  'ls\d' to match ls1, ls2, ls3 etc
    containsTxt:        List of Strings, only finds file if it contains this text.  Ignore if '' (or blank)
    subFolders:         Bool.  If True, find files in all subfolders under path. If False, only searches files in the specified folder
    excludeText:        Text string.  Ignore if ''. Will exclude if text string is in path.
    """
    if type(containsTxt) == str: # if a string and not in a list
        containsTxt = [containsTxt]
    
    myregexobj = re.compile('\.' + extension + '$')    # Makes sure the file extension is at the end and is preceded by a .
    
    try:   # Trapping a OSError or FileNotFoundError:  File permissions problem I believe
        for entry in os.scandir(path):
            if entry.is_file() and myregexobj.search(entry.path): # 
    
                bools = [True for txt in containsTxt if txt in entry.path and (excludeText == '' or excludeText not in entry.path)]
    
                if len(bools)== len(containsTxt):
                    yield entry.stat().st_size, entry.stat().st_atime_ns, entry.stat().st_mtime_ns, entry.stat().st_ctime_ns, entry.path
    
            elif entry.is_dir() and subFolders:   # if its a directory, then repeat process as a nested function
                yield from findFilesInFolderYield(entry.path,  extension, containsTxt, subFolders)
    except OSError as ose:
        print('Cannot access ' + path +'. Probably a permissions error ', ose)
    except FileNotFoundError as fnf:
        print(path +' not found ', fnf)

def findFilesInFolderYieldandGetDf(path,  extension, containsTxt, subFolders = True, excludeText = ''):
    """  Converts returned data from findFilesInFolderYield and creates and Pandas Dataframe.
    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
    extension:          File extension to find.  e.g. 'txt'.  Regular expression. Or  'ls\d' to match ls1, ls2, ls3 etc
    containsTxt:        List of Strings, only finds file if it contains this text.  Ignore if '' (or blank)
    subFolders:         Bool.  If True, find files in all subfolders under path. If False, only searches files in the specified folder
    excludeText:        Text string.  Ignore if ''. Will exclude if text string is in path.
    """
    
    fileSizes, accessTimes, modificationTimes, creationTimes , paths  = zip(*findFilesInFolderYield(path,  extension, containsTxt, subFolders))
    df = pd.DataFrame({
            'FLS_File_Size':fileSizes,
            'FLS_File_Access_Date':accessTimes,
            'FLS_File_Modification_Date':np.array(modificationTimes).astype('timedelta64[ns]'),
            'FLS_File_Creation_Date':creationTimes,
            'FLS_File_PathName':paths,
                  })
    
    df['FLS_File_Modification_Date'] = pd.to_datetime(df['FLS_File_Modification_Date'],infer_datetime_format=True)
    df['FLS_File_Creation_Date'] = pd.to_datetime(df['FLS_File_Creation_Date'],infer_datetime_format=True)
    df['FLS_File_Access_Date'] = pd.to_datetime(df['FLS_File_Access_Date'],infer_datetime_format=True)

    return df

ext =   'txt'  # regular expression 
containsTxt=[]
path = 'C:\myFolder'
df = findFilesInFolderYieldandGetDf(path,  ext, containsTxt, subFolders = True)

A
Anuvrat Parashar

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 f in p.walk(pattern='*.txt') 浏览每个子文件夹
是的,还有 pathlib。您可以执行以下操作:list(p.glob('**/*.py'))
X
Xxxo

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))

如果您希望 all_txt_files 成为列表:all_txt_files = list(filter(lambda x: x.endswith('.txt'), os.listdir(the_dir)))
A
Arsen Khachaturyan

以 Pythonic 方式将 'dataPath' 文件夹中的所有 '.txt' 文件名作为列表获取:

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

u
user136036

我做了一个测试(Python 3.6.4,W7x64),看看哪个解决方案对于一个文件夹来说是最快的,没有子目录,以获得具有特定扩展名的文件的完整文件路径列表。

简而言之,对于这个任务,os.listdir() 是最快的,是次优的 1.7 倍:os.walk()(稍作休息!),是 pathlib 的 2.7 倍,比 {4 快 3.2 倍} 并且比 glob 快 3.3 倍。
请记住,当您需要递归结果时,这些结果会发生变化。如果您在下面复制/粘贴一种方法,请添加 .lower() 否则搜索 .ext 时将找不到 .EXT。

import os
import pathlib
import timeit
import glob

def a():
    path = pathlib.Path().cwd()
    list_sqlite_files = [str(f) for f in path.glob("*.sqlite")]

def b(): 
    path = os.getcwd()
    list_sqlite_files = [f.path for f in os.scandir(path) if os.path.splitext(f)[1] == ".sqlite"]

def c():
    path = os.getcwd()
    list_sqlite_files = [os.path.join(path, f) for f in os.listdir(path) if f.endswith(".sqlite")]

def d():
    path = os.getcwd()
    os.chdir(path)
    list_sqlite_files = [os.path.join(path, f) for f in glob.glob("*.sqlite")]

def e():
    path = os.getcwd()
    list_sqlite_files = [os.path.join(path, f) for f in glob.glob1(str(path), "*.sqlite")]

def f():
    path = os.getcwd()
    list_sqlite_files = []
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith(".sqlite"):
                list_sqlite_files.append( os.path.join(root, file) )
        break



print(timeit.timeit(a, number=1000))
print(timeit.timeit(b, number=1000))
print(timeit.timeit(c, number=1000))
print(timeit.timeit(d, number=1000))
print(timeit.timeit(e, number=1000))
print(timeit.timeit(f, number=1000))

结果:

# Python 3.6.4
0.431
0.515
0.161
0.548
0.537
0.274

Python 3.6.5 文档指出: os.scandir() 函数返回目录条目以及文件属性信息,在许多常见用例中提供更好的性能[比 os.listdir()]。
我错过了这个测试的缩放范围你在这个测试中使用了多少个文件?如果您放大/缩小数字,它们如何比较?
m
mrgloom
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

K
Kamen Tsvetkov

要从同一目录中名为“data”的文件夹中获取“.txt”文件名数组,我通常使用以下简单的代码行:

import os
fileNames = [fileName for fileName in os.listdir("data") if fileName.endswith(".txt")]

p
praba230890

这段代码让我的生活更简单。

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)

y
yucer

使用 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

M
Martin Thoma

一种类似于 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

您还可以使用 yield 创建生成器,从而避免组装完整列表:

def get_all_filepaths(root_path, ext):
    import os
    for root, dirs, files in os.walk(root_path):
        for filename in files:
            if filename.lower().endswith(ext):
                yield os.path.join(root, filename)

@ghostdog 答案的主要缺陷是区分大小写。在许多情况下,此处使用 lower() 至关重要。谢谢!但我猜 doctest 行不通,对在许多情况下,使用 yield 的解决方案也可能更好。
@nealmcb 我不知道如何为使用本地文件系统的函数编写简短的文档测试😄 对我来说,文档字符串的主要目的是与人类交流。如果文档字符串有助于理解函数在做什么,那么它就是一个很好的文档字符串。
关于产量:是的,这肯定是个好主意!调整它以使用 yield 是微不足道的。我想让答案对初学者友好,这意味着避免产量......也许我稍后会添加它🤔
N
Nicolaesse

我建议你使用 fnmatch 和上面的方法。通过这种方式,您可以找到以下任何内容:

名称.txt;名称.TXT;名称.txt

.

import fnmatch
import os

    for file in os.listdir("/Users/Johnny/Desktop/MyTXTfolder"):
        if fnmatch.fnmatch(file.upper(), '*.TXT'):
            print(file)

E
Efreeto

这是一个带有 extend()

types = ('*.jpg', '*.png')
images_list = []
for files in types:
    images_list.extend(glob.glob(os.path.join(path, files)))

不适用于 .txt :)
A
Adam Chrapkowski

带有子目录的功能解决方案:

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"))))

从长远来看,您是否希望维护此代码?
t
tashuhka

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

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')]

R
Rajiv Sharma

使用 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

k
kfsone

许多用户回复了 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)]