在Python中的扩展.txt文件中找到所有文件。

时间:2022-04-11 19:26:57

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

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

31 个解决方案

#1


1565  

You can use glob:

你可以用一团:

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

or simply os.listdir:

或者只是os.listdir:

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

or if you want to traverse directory, use os.walk:

或者,如果您想要遍历目录,可以使用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


169  

Use glob.

用一团。

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

#3


114  

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

#4


82  

Something like this will work:

像这样的东西会起作用:

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

#5


25  

I like os.walk():

我喜欢os.walk():

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

Or with generators:

或与发电机:

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

#6


23  

import os

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

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

#7


20  

Here's more versions of the same that produce slightly different results:

这里有更多相同的版本,产生的结果略有不同:

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

#8


17  

path.py is another alternative: https://github.com/jaraco/path.py

路径。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

#9


9  

Python has all tools to do this:

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


8  

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

#11


7  

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)

#12


5  

You can try this code

您可以试试这段代码。

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

#13


5  

Use fnmatch: https://docs.python.org/2/library/fnmatch.html

使用:https://docs.python.org/2/library/fnmatch.html

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print file

#14


5  

You can simply use pathlibs glob 1:

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

如果你希望它是递归的,你可以使用。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.

pathlib模块被包含在python 3.4中的标准库中。但是您可以在旧的Python版本(即使用conda或pip): pathlib和pathlib2上安装该模块的后端口。

#15


3  

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

For me. It's classic.

给我。它的经典。

#16


3  

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

我建议您使用fnmatch和upper方法。通过这种方式,你可以找到以下任何一个:

  1. Name.txt;
  2. Name.txt;
  3. Name.TXT;
  4. Name.TXT;
  5. Name.Txt
  6. Name.Txt

.

import fnmatch
import os

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

#17


3  

I did a test (Python 3.6.4, W7x64) to see which solution is the fastest for one folder, no subdirectories, to get a list of complete file paths for files with a specific extension.

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

To make it short, for this task os.listdir() is the fastest and is 1.7x as fast as the next best: os.walk() (with a break!), 2.7x as fast as pathlib, 3.2x faster than os.scandir() and 3.3x faster than glob.
Please keep in mind, that those results will change when you need recursive results. If you copy/paste one method below, please add a .lower() otherwise .EXT would not be found when searching for .ext.

为了使它简短,这个任务os.listdir()是最快的,它的速度是下一个最好的:os.walk()(有一个break!), 2.7x和pathlib一样快,比os.scandir快3倍,比glob快3倍。请记住,当您需要递归的结果时,这些结果将会改变。如果您在下面复制/粘贴一个方法,请添加一个.lower(),否则在搜索.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))

Results:

结果:

# Python 3.6.4
0.431
0.515
0.161
0.548
0.537
0.274

#18


2  

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

#19


2  

In case the folder contains a lot of files or memory is an constraint, consider using generators:

如果文件夹包含大量文件或内存是一个约束,请考虑使用生成器:

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

Option A: Iterate

选项一:迭代

for f in yield_files_with_extensions('.', '.txt'): 
    print(f)

Option B: Get all

选项B:获得所有

files = [f for f in yield_files_with_extensions('.', '.txt')]

#20


2  

import glob
import os

path=os.getcwd()

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

for i in extensions:
  for files in glob.glob(i):
     print files

#21


2  

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

#22


2  

A copy-pastable solution similar to the one of ghostdog:

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

#23


2  

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

得到所有”。将“dataPath”文件夹内的txt文件名称以python的方式列出。

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

#24


1  

You can try this code:

您可以试试下面的代码:

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

#25


1  

use Python OS module to find files with specific extension.

使用Python OS模块查找具有特定扩展的文件。

the simple example is here :

这里有一个简单的例子:

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

#26


1  

Try this this will find all your file inside folder or folder

试试这个,你会发现你所有的文件都在文件夹或文件夹里。

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)

#27


1  

Many users have replied with os.walk answers, which includes all files but also all directories and subdirectories and their files.

许多用户已经回复了操作系统。walk answers,包括所有文件,但也包括所有目录和子目录及其文件。

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)

Or for a one off where you don't need a generator:

或者是你不需要发电机的地方:

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)

If you are going to use matches for something else, you may want to make it a list rather than a generator expression:

如果您要使用匹配的其他东西,您可能希望将它作为一个列表,而不是生成器表达式:

    matches = [f for f in dirfiles if f.endswith(ext)]

#28


1  

Here's one with extend()

这是一个扩展()

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

#29


0  

import os
[x for x in os.listdir() if x.endswith(".txt")]

HOW MANY FILES IN DIR AND SUBDIRS ?

If you want to know how many filese there are in a dir and subdirs:

如果你想知道在一个dir和subdirs中有多少个filese:

In this example, we look for the number of files that are included in all the directory and its subdirecories.

在本例中,我们查找包含在所有目录及其子目录中的文件的数量。

import os    

def count(dir, counter=0):
    "returns number of files in dir and subdirs"
    for pack in os.walk(dir):
        for f in pack[2]:
            counter += 1
    return dir + " : " + str(counter) + "files"


print(count("F:\\python"))

output

输出

'F:\python' : 12057 files'

F:\ python的:12057个文件

#30


0  

A simple method by using for loop :

一种简单的循环利用方法:

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

Though this can be made more generalised .

尽管这可以更加一般化。

#1


1565  

You can use glob:

你可以用一团:

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

or simply os.listdir:

或者只是os.listdir:

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

or if you want to traverse directory, use os.walk:

或者,如果您想要遍历目录,可以使用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


169  

Use glob.

用一团。

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

#3


114  

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

#4


82  

Something like this will work:

像这样的东西会起作用:

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

#5


25  

I like os.walk():

我喜欢os.walk():

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

Or with generators:

或与发电机:

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

#6


23  

import os

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

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

#7


20  

Here's more versions of the same that produce slightly different results:

这里有更多相同的版本,产生的结果略有不同:

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

#8


17  

path.py is another alternative: https://github.com/jaraco/path.py

路径。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

#9


9  

Python has all tools to do this:

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


8  

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

#11


7  

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)

#12


5  

You can try this code

您可以试试这段代码。

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

#13


5  

Use fnmatch: https://docs.python.org/2/library/fnmatch.html

使用:https://docs.python.org/2/library/fnmatch.html

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print file

#14


5  

You can simply use pathlibs glob 1:

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

如果你希望它是递归的,你可以使用。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.

pathlib模块被包含在python 3.4中的标准库中。但是您可以在旧的Python版本(即使用conda或pip): pathlib和pathlib2上安装该模块的后端口。

#15


3  

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

For me. It's classic.

给我。它的经典。

#16


3  

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

我建议您使用fnmatch和upper方法。通过这种方式,你可以找到以下任何一个:

  1. Name.txt;
  2. Name.txt;
  3. Name.TXT;
  4. Name.TXT;
  5. Name.Txt
  6. Name.Txt

.

import fnmatch
import os

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

#17


3  

I did a test (Python 3.6.4, W7x64) to see which solution is the fastest for one folder, no subdirectories, to get a list of complete file paths for files with a specific extension.

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

To make it short, for this task os.listdir() is the fastest and is 1.7x as fast as the next best: os.walk() (with a break!), 2.7x as fast as pathlib, 3.2x faster than os.scandir() and 3.3x faster than glob.
Please keep in mind, that those results will change when you need recursive results. If you copy/paste one method below, please add a .lower() otherwise .EXT would not be found when searching for .ext.

为了使它简短,这个任务os.listdir()是最快的,它的速度是下一个最好的:os.walk()(有一个break!), 2.7x和pathlib一样快,比os.scandir快3倍,比glob快3倍。请记住,当您需要递归的结果时,这些结果将会改变。如果您在下面复制/粘贴一个方法,请添加一个.lower(),否则在搜索.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))

Results:

结果:

# Python 3.6.4
0.431
0.515
0.161
0.548
0.537
0.274

#18


2  

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

#19


2  

In case the folder contains a lot of files or memory is an constraint, consider using generators:

如果文件夹包含大量文件或内存是一个约束,请考虑使用生成器:

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

Option A: Iterate

选项一:迭代

for f in yield_files_with_extensions('.', '.txt'): 
    print(f)

Option B: Get all

选项B:获得所有

files = [f for f in yield_files_with_extensions('.', '.txt')]

#20


2  

import glob
import os

path=os.getcwd()

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

for i in extensions:
  for files in glob.glob(i):
     print files

#21


2  

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

#22


2  

A copy-pastable solution similar to the one of ghostdog:

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

#23


2  

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

得到所有”。将“dataPath”文件夹内的txt文件名称以python的方式列出。

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

#24


1  

You can try this code:

您可以试试下面的代码:

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

#25


1  

use Python OS module to find files with specific extension.

使用Python OS模块查找具有特定扩展的文件。

the simple example is here :

这里有一个简单的例子:

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

#26


1  

Try this this will find all your file inside folder or folder

试试这个,你会发现你所有的文件都在文件夹或文件夹里。

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)

#27


1  

Many users have replied with os.walk answers, which includes all files but also all directories and subdirectories and their files.

许多用户已经回复了操作系统。walk answers,包括所有文件,但也包括所有目录和子目录及其文件。

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)

Or for a one off where you don't need a generator:

或者是你不需要发电机的地方:

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)

If you are going to use matches for something else, you may want to make it a list rather than a generator expression:

如果您要使用匹配的其他东西,您可能希望将它作为一个列表,而不是生成器表达式:

    matches = [f for f in dirfiles if f.endswith(ext)]

#28


1  

Here's one with extend()

这是一个扩展()

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

#29


0  

import os
[x for x in os.listdir() if x.endswith(".txt")]

HOW MANY FILES IN DIR AND SUBDIRS ?

If you want to know how many filese there are in a dir and subdirs:

如果你想知道在一个dir和subdirs中有多少个filese:

In this example, we look for the number of files that are included in all the directory and its subdirecories.

在本例中,我们查找包含在所有目录及其子目录中的文件的数量。

import os    

def count(dir, counter=0):
    "returns number of files in dir and subdirs"
    for pack in os.walk(dir):
        for f in pack[2]:
            counter += 1
    return dir + " : " + str(counter) + "files"


print(count("F:\\python"))

output

输出

'F:\python' : 12057 files'

F:\ python的:12057个文件

#30


0  

A simple method by using for loop :

一种简单的循环利用方法:

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

Though this can be made more generalised .

尽管这可以更加一般化。