Hướng dẫn how to get the list of files with specified extension in python? - cách lấy danh sách các tệp có phần mở rộng được chỉ định trong python?

Python v3.5+

Phương pháp nhanh bằng cách sử dụng OS.Scandir trong một hàm đệ quy. Tìm kiếm tất cả các tệp với một tiện ích mở rộng được chỉ định trong thư mục và trình phụ phụ. Nó là nhanh, ngay cả khi tìm thấy 10.000 tệp.

Tôi cũng đã bao gồm một chức năng để chuyển đổi đầu ra thành khung dữ liệu gấu trúc.

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]

. Readme.md ',' aborment.txt ',' main.py ']]

.

  • Phương pháp 2: Sử dụng mô -đun `glob`The OS module in Python provides functions for interacting with the operating system.
  • Mô -đun GLOB tìm thấy tất cả các tên đường dẫn khớp với một mẫu được chỉ định theo các quy tắc được sử dụng bởi vỏ Unix. Chúng tôi sẽ sử dụng hàm glob.glob [] để đạt được nhiệm vụ của chúng tôi. Ý tưởng đằng sau UNIX Shell giống như có nghĩa là chúng ta có thể cung cấp các mẫu giống như shell để tìm kiếm các tệp.In Python, the glob module is used to retrieve files/pathnames matching a specified pattern. The pattern rules of glob follow standard Unix path expansion rules. It is also predicted that according to benchmarks it is faster than other methods to match pathnames in directories.

& nbsp; glob.glob [pathName, *, recursive = false]

Trả về một danh sách các tên đường dẫn khớp tên đường dẫn, phải là một chuỗi chứa thông số kỹ thuật đường dẫn.

‘**Có nghĩa là nó sẽ khớp với tất cả các mục được trả về bằng phương thức Os.ListDir [].

Ví dụ 1: Nhận tất cả các thư mục và tệp trong root/home/project/mã

import "root/home/project"8os.listdir[] lists all the files present in a directory. We can make use of os.walk[] if we want to work with sub-directories as well.

Syntax:

"root/home/project"9=

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
01
['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
022
os.listdir[path = ‘.’]

.

Syntax:

Ví dụ 2: Nhận tất cả các tệp python [.py] trong root/home/urpaness/code/code/database_models

"root/home/project"9=

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
01
['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
11
['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
0

[‘Lược đồ_template.py,‘ sqlalchemy_models.py,]] List the files and directories present in root/home/project

Python

import os

=5= =77____78

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
1
['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
2

=9= =77____78

import0 r4import2 r6"root/home/project"r8

. Readme.md ',' aborment.txt ',' main.py ']]

os0os1

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
1os3

Ví dụ 1.5: Chỉ liệt kê các tệp, bằng cách sử dụng chức năng OS.Path.isFile.List only the files, by using os.path.isfile function.

Python3

import os

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
1os7os8
['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
0

list_1 0= list_1 2list_1 3list_1 44

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
1list_1 7list_1 8
['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
0

=0= =2

=0= =5import0 =7import2

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
1os7os.listdir[path8os.listdir[path9==1
['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
0

Đầu ra:

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']

Ví dụ 2: Liệt kê tất cả các thư mục con và phụ kiện phụ có mặt trong root/home/dự ánList all the subdirectories and sub-files present in root/home/project

Python

import os

list_1 0= list_1 2list_1 3list_1 44

=0= =2

=0= =5import0 =7import2

import4"root/home/project"0

import4"root/home/project"2

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
1"root/home/project"4

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
1"root/home/project"6

Output:

Đầu ra:

.

Phương pháp 2: Sử dụng mô -đun `glob`

Mô -đun GLOB tìm thấy tất cả các tên đường dẫn khớp với một mẫu được chỉ định theo các quy tắc được sử dụng bởi vỏ Unix. Chúng tôi sẽ sử dụng hàm glob.glob [] để đạt được nhiệm vụ của chúng tôi. Ý tưởng đằng sau UNIX Shell giống như có nghĩa là chúng ta có thể cung cấp các mẫu giống như shell để tìm kiếm các tệp.glob.glob[] function to achieve our task. The idea behind Unix shell-like means that we can provide Unix shell-like patterns for searching files.

Syntax:

& nbsp; glob.glob [pathName, *, recursive = false]glob.glob[pathname, *, recursive=False]

Trả về một danh sách các tên đường dẫn khớp tên đường dẫn, phải là một chuỗi chứa thông số kỹ thuật đường dẫn.

‘**Có nghĩa là nó sẽ khớp với tất cả các mục được trả về bằng phương thức Os.ListDir [].*‘ means that it will match all the items returned by similar to os.listdir[] method.

Ví dụ 1: Nhận tất cả các thư mục và tệp trong root/home/project/mã Get all the directories and files in root/home/project/code

Python

import "root/home/project"8

"root/home/project"9=

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
01
['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
022

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
1
['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
05

Output:

.

Ví dụ 2: Nhận tất cả các tệp python [.py] trong root/home/urpaness/code/code/database_models Get all the python [.py] files in root/home/project/code/database_models

Python

import "root/home/project"8

"root/home/project"9=

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
01
['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
022

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
1
['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
05

Output:

.


Bài Viết Liên Quan

Chủ Đề