Hướng dẫn python glob files with extension - tập tin toàn cầu python với phần mở rộng

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)

Trong hướng dẫn Python này, chúng ta sẽ xem cách liệt kê tất cả các tệp của một thư mục có một phần mở rộng cụ thể.

Đôi khi chúng ta cần liệt kê các tệp có một tiện ích mở rộng cụ thể trước khi thực hiện bất kỳ hoạt động nào trên chúng. Ví dụ: nếu bạn muốn chỉ sao chép các tệp văn bản từ vị trí này sang vị trí khác. Trong trường hợp này, chúng tôi cần đảm bảo rằng chúng tôi chỉ đang tìm kiếm các tệp có tiện ích mở rộng

sales.txt
profit.txt
samples.txt
0.

Chúng tôi sẽ sử dụng các phương thức sau & nbsp; ba phương thức.three methods.

Phần mở rộng tệp hoặc tiện ích mở rộng tệp, là một hậu tố ở cuối tệp. Nó đến sau thời gian. Tiện ích mở rộng Chỉ định một loại tệp như văn bản, tệp CSV, PDF hoặc tệp hình ảnh. Ví dụ: đối với một tệp văn bản, đó là

sales.txt
profit.txt
samples.txt
1. Đối với tệp hình ảnh, đó là
sales.txt
profit.txt
samples.txt
2,
sales.txt
profit.txt
samples.txt
3 hoặc
sales.txt
profit.txt
samples.txt
4.

Dưới đây là các bước để có được danh sách các tệp có phần mở rộng TXT bằng mô -đun GLOB.

  1. Nhập mô -đun Quả cầu

    Mô -đun GLOB, một phần của thư viện tiêu chuẩn Python, được sử dụng để & nbsp; tìm các tệp và thư mục có tên theo một mẫu cụ thể. Các quy tắc tìm kiếm tương tự như các quy tắc mở rộng đường dẫn Unix Shell.find the files and folders whose names follow a specific pattern. The searching rules are similar to the Unix Shell path expansion rules.

  2. Xây dựng một mẫu để tìm kiếm các tệp có phần mở rộng cụ thể

    Ví dụ:

    sales.txt
    profit.txt
    samples.txt
    5 để liệt kê tất cả các tệp văn bản có trong một đường dẫn thư mục nhất định. Ở đây
    sales.txt
    profit.txt
    samples.txt
    6 có nghĩa là tên tệp có thể là bất cứ điều gì, nhưng nó phải có tiện ích mở rộng
    sales.txt
    profit.txt
    samples.txt
    1.

  3. Sử dụng phương thức glob ()

    Phương thức

    sales.txt
    profit.txt
    samples.txt
    8 trả về một danh sách các tệp phù hợp với đường dẫn và mẫu được chỉ định trong đối số tên đường dẫn. Trong trường hợp này, nó sẽ trả về tất cả các tệp văn bản.

Ví dụ: Liệt kê các tệp trong thư mục với TXT mở rộng

Các tệp văn bản sau đây có trong thư mục làm việc hiện tại của tôi.

sales.txt
profit.txt
samples.txt

Ví dụ 1: Liệt kê tất cả các tệp

sales.txt
profit.txt
samples.txt
1 có trong thư mục ‘Tài khoản.: List all
sales.txt
profit.txt
samples.txt
1 files present in the ‘account’ directory.

import glob

# absolute path to search all text files inside a specific folder
path = r'E:/demos/files_demos/account/*.txt'
files = glob.glob(path)
print(files)

Output::

['E:/account\\profit.txt', 'E:/account\\sales.txt', 'E:/account\\sample.txt']

Nếu bạn muốn liệt kê các tệp từ thư mục hiện tại, việc sử dụng

import glob

# absolute path to search all text files inside a specific folder
path = r'E:/demos/files_demos/account/*.txt'
files = glob.glob(path)
print(files)
0.

Lưu ý: Giải pháp này nhanh vì nó chỉ tìm kiếm một mẫu cụ thể thay vì đi qua toàn bộ tệp thư mục bằng tệp để kiểm tra xem nó có mở rộng cụ thể không, dẫn đến lợi ích hiệu suất.: This solution is fast because it only looks for a specific pattern instead of traversing the entire directory file by file to check if it has a specific extension, resulting in performance benefits.

Mô -đun hệ điều hành để liệt kê các tệp trong thư mục với phần mở rộng

Mô-đun này giúp chúng tôi làm việc với chức năng phụ thuộc hệ điều hành trong Python. Mô -đun OS cung cấp các chức năng để tương tác với hệ điều hành.

Sử dụng các bước dưới đây: -

  • Sử dụng chức năng
    import glob
    
    # absolute path to search all text files inside a specific folder
    path = r'E:/demos/files_demos/account/*.txt'
    files = glob.glob(path)
    print(files)
    
    1 để lấy danh sách tất cả các tệp của một thư mục. Hàm này trả về tên của các tệp và thư mục có trong thư mục.
  • Tiếp theo, sử dụng một vòng lặp để lặp lại tất cả các tệp từ một danh sách.
  • Tiếp theo, sử dụng điều kiện IF trong mỗi lần lặp để kiểm tra xem tên tệp có kết thúc bằng phần mở rộng TXT không. Nếu có, hãy thêm nó vào danh sách cuối cùng

Example::

import os

# folder path
dir_path = r'E:\account'

# list to store files
res = []
# Iterate directory
for file in os.listdir(dir_path):
    # check only text files
    if file.endswith('.txt'):
        res.append(file)
print(res)

Output::

['profit.txt', 'sales.txt', 'sample.txt']

Lưu ý: Giải pháp này chậm vì nó đi qua toàn bộ tệp thư mục bằng tệp để kiểm tra xem nó có mở rộng cụ thể không, dẫn đến chi phí hiệu suất nếu thư mục chứa nhiều tệp. Vì vậy, tôi khuyên bạn nên sử dụng giải pháp đầu tiên, tức là, mô -đun toàn cầu.: This solution is slow because it traverses the entire directory file by file to check if it has a specific extension, resulting in performance overhead if the directory contains many files. So I suggest you use the first solution, i.e., glob module.

Liệt kê các tệp trong thư mục và thư mục con với TXT mở rộng

Chúng ta có thể sử dụng hai cách tiếp cận sau: -

  • Mô -đun Quả cầu
  • Hàm
    import glob
    
    # absolute path to search all text files inside a specific folder
    path = r'E:/demos/files_demos/account/*.txt'
    files = glob.glob(path)
    print(files)
    
    2

Mô -đun GLOB để liệt kê các tệp từ các thư mục con với TXT mở rộng

Đặt & nbsp; ____ 23 & nbsp; thuộc tính của phương thức

import glob

# absolute path to search all text files inside a specific folder
path = r'E:/demos/files_demos/account/*.txt'
files = glob.glob(path)
print(files)
4 thành true để liệt kê các tệp văn bản từ các thư mục con.

Sử dụng Python 3.5+ để tìm các tệp một cách đệ quy bằng mô -đun GLOB. Nếu bạn đang sử dụng phiên bản Python cũ hơn, thì hãy sử dụng phương thức

import glob

# absolute path to search all text files inside a specific folder
path = r'E:/demos/files_demos/account/*.txt'
files = glob.glob(path)
print(files)
2.3.5+ to find files recursively using the glob module. If you are using the older version of Python, then use the
import glob

# absolute path to search all text files inside a specific folder
path = r'E:/demos/files_demos/account/*.txt'
files = glob.glob(path)
print(files)
2 method.

Mô -đun & nbsp; Glob hỗ trợ & nbsp; ____ ____ 26 & nbsp; Chỉ thị. Nếu bạn muốn nó đệ quy, bạn có thể sử dụng

import glob

# absolute path to search all text files inside a specific folder
path = r'E:/demos/files_demos/account/*.txt'
files = glob.glob(path)
print(files)
7 và đặt cờ đệ quy thành
import glob

# absolute path to search all text files inside a specific folder
path = r'E:/demos/files_demos/account/*.txt'
files = glob.glob(path)
print(files)
8, phương thức glob () phân tích con đường đã cho và trông đệ quy trong các thư mục.glob module supports the 
import glob

# absolute path to search all text files inside a specific folder
path = r'E:/demos/files_demos/account/*.txt'
files = glob.glob(path)
print(files)
6 directive
. If you want it recursive you can use
import glob

# absolute path to search all text files inside a specific folder
path = r'E:/demos/files_demos/account/*.txt'
files = glob.glob(path)
print(files)
7 and set a recursive flag to
import glob

# absolute path to search all text files inside a specific folder
path = r'E:/demos/files_demos/account/*.txt'
files = glob.glob(path)
print(files)
8, the glob() method parses the given path and looks recursively in the directories.

Example::

import glob

# absolute path to search all text files inside a specific folder
path = r'E:/account/**/*.txt'
files = glob.glob(path, recursive=True)
print(files)

Output::

['E:/account\\profit.txt', 'E:/account\\sales.txt', 'E:/account\\sample.txt', 'E:/account\\reports_2021\\december_2021.txt']

import glob # absolute path to search all text files inside a specific folder path = r'E:/demos/files_demos/account/*.txt' files = glob.glob(path) print(files) 2 để liệt kê các tệp trong thư mục và thư mục con với TXT mở rộng

Đó là hàm đệ quy A & nbsp; mỗi khi trình tạo được gọi là nó tạo ra một bộ giá trị (current_path, thư mục trong current_path, file in current_path) và nó sẽ theo từng thư mục để lấy danh sách các tệp và thư mục cho đến khi không còn nữa Các thư mục con có sẵn từ thư mục ban đầu.recursive function, i.e., Every time the generator is called it creates a tuple of values (current_path, directories in current_path, files in current_path) and it will follow each directory recursively to get a list of files and directories until no further sub-directories are available from the initial directory.

  • Gọi hàm
    ['E:/account\\profit.txt', 'E:/account\\sales.txt', 'E:/account\\sample.txt']
    0. Nó sẽ mang lại hai danh sách cho mỗi thư mục mà nó truy cập. Danh sách đầu tiên chứa các tập tin và danh sách thứ hai bao gồm các thư mục.
  • Tiếp theo, lặp lại danh sách các tệp bằng cách sử dụng một vòng lặp
  • Tiếp theo, sử dụng điều kiện IF trong mỗi lần lặp để kiểm tra xem tên tệp có kết thúc bằng phần mở rộng TXT không. Nếu có, hãy thêm nó vào danh sách cuối cùng.

Example::

import os

# list to store txt files
res = []
# os.walk() returns subdirectories, file from current directory and 
# And follow next directory from subdirectory list recursively until last directory
for root, dirs, files in os.walk(r"E:\demos\files_demos\account"):
    for file in files:
        if file.endswith(".txt"):
            res.append(os.path.join(root, file))
print(res)
['E:/account\\profit.txt', 'E:/account\\sales.txt', 'E:/account\\sample.txt', 'E:/account\\reports_2021\\december_2021.txt']

Bài tập và câu đố Python

Các bài tập mã hóa miễn phí và các câu đố bao gồm các vấn đề cơ bản của Python, cấu trúc dữ liệu, phân tích dữ liệu, v.v.

  • Hơn 15 bài tập và câu đố dành riêng cho chủ đềTopic-specific Exercises and Quizzes
  • Mỗi bài tập chứa 10 câu hỏi
  • Mỗi bài kiểm tra chứa 12-15 mcq

Có nghĩa là * có nghĩa là gì trong Python trong GLOB?

Theo Wikipedia, các mẫu Glob Glob chỉ định các bộ tệp với ký tự ký tự đại diện.Các mẫu này tương tự như biểu thức thông thường nhưng đơn giản hơn nhiều.Asterisk (*): khớp với số không hoặc nhiều ký tự.Dấu hỏi (?) Khớp với chính xác một ký tự.Matches zero or more characters. Question Mark (?) Matches exactly one character.

Có bao gồm toàn cầu trong Python?

Mô -đun GLOB là một phần hữu ích của thư viện tiêu chuẩn Python.Tóm lại cho toàn cầu, Glob được sử dụng để trả về tất cả các đường dẫn tệp phù hợp với một mẫu cụ thể.