Hướng dẫn how do you list all files in a directory with a certain extension in python? - làm cách nào để liệt kê tất cả các tệp trong một thư mục với một phần mở rộng nhất đị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)

import0 r4import2 r6"root/home/project"r8

Các mô -đun được sử dụng

  • HĐH: Mô -đun HĐH trong Python cung cấp các chức năng để tương tác với hệ điều hành.The OS module in Python provides functions for interacting with the operating system.
  • GLOB: Trong Python, mô -đun GLOB được sử dụng để truy xuất các tệp/tên đường dẫn khớp với một mẫu được chỉ định. Các quy tắc mẫu của GLOB tuân theo các quy tắc mở rộng đường dẫn Unix tiêu chuẩn. Người ta cũng dự đoán rằng theo điểm chuẩn, nó nhanh hơn các phương pháp khác để khớp các tên đường dẫn trong các thư mục.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.

Cấu trúc thư mục đang sử dụng:

Hướng dẫn how do you list all files in a directory with a certain extension in python? - làm cách nào để liệt kê tất cả các tệp trong một thư mục với một phần mở rộng nhất định trong python?

Cấu trúc thư mục Chế độ xem gốc

Hướng dẫn how do you list all files in a directory with a certain extension in python? - làm cách nào để liệt kê tất cả các tệp trong một thư mục với một phần mở rộng nhất định trong python?

Tệp thư mục biểu diễn trực quan

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

Mô-đun này cung cấp một cách di động để sử dụng chức năng phụ thuộc hệ điều hành. Phương thức Os.ListDir () liệt kê tất cả các tệp có trong một thư mục. Chúng ta có thể sử dụng os.walk () nếu chúng ta cũng muốn làm việc với các thư mục phụ.os.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:

& nbsp; os.listdir (path = ‘.os.listdir(path = ‘.’)

Trả về một danh sách chứa tên của các mục trong thư mục được đưa ra bởi đường dẫn. & NBSP;

Syntax:

& nbsp; os.walk (top, topDown = true, onerror = none

Tạo tên tệp trong cây thư mục bằng cách đi bộ từ từ trên xuống hoặc từ dưới lên.

Ví dụ 1: Liệt kê các tệp và thư mục có trong root/home/dự án List the files and directories present in root/home/project

Python

import os

list_1 = os.listdir(path=______8

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

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
3= os.listdir(path=______8

import0 import1import2 import3

import4import5 import6 import7 import2 import9

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 = os.listdir(path=______8

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

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
3= os.listdir(path=______8

import0 import1import2 import3

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

import4import5 import6 import7 import2 import9

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

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 all the subdirectories and sub-files present in root/home/project

Python

import os

list_1 = os.listdir(path=______8

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
3= os.listdir(path=______8

import0 import1import2 import3

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:

import4import5 import6 import7 import2 import9

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_1 0= list_1 2list_1 3list_1 44

=0= =2glob.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:

=0= =5import0 =7import2glob.glob(pathname, *, recursive=False)

Đầu ra:

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ự án*‘ means that it will match all the items returned by similar to os.listdir() method.

=5= =77____78 Get all the directories and files in root/home/project/code

Python

import os

list_1 = os.listdir(path=______8

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

Output:

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
3= os.listdir(path=______8

import0 import1import2 import3 Get all the python (.py) files in root/home/project/code/database_models

Python

import os

list_1 = os.listdir(path=______8

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

Output:

['documents', 'code', 'charter.xlsx', 'timeline.jpg']
['charter.xlsx', 'timeline.jpg']
3= os.listdir(path=______8


Làm cách nào để thấy tất cả các phần mở rộng tệp trong Python?

Khoa học dữ liệu thực tế bằng cách sử dụng Python, bạn có thể sử dụng phương thức OS.ListDir để có tất cả các thư mục và tệp trong một thư mục.Sau đó lọc danh sách để chỉ nhận các tệp và kiểm tra các phần mở rộng của chúng.use the os. listdir method to get all directories and files in a directory. Then filter the list to get only the files and check their extensions as well.

Làm thế nào để bạn có được đường dẫn của tất cả các tệp trong một thư mục trong Python?

Phương pháp 1: Mô -đun HĐH..
Cú pháp: Os.ListDir (đường dẫn).
Parameters:.
Loại trả về: Trả về danh sách tất cả các tệp và thư mục trong đường dẫn được chỉ định ..

Làm thế nào tôi có thể liệt kê tất cả các tệp của một thư mục trong Python và thêm chúng vào danh sách?

Sử dụng các hàm listddir () và isfile () của mô -đun HĐH để liệt kê tất cả các tệp của một thư mục. to list all files of a directory.

Làm thế nào để bạn tìm thấy tất cả các tệp .txt trong bất kỳ thư mục python?

Phương thức Os.ListDir () liệt kê tất cả các tệp có trong một thư mục.os. listdir() lists all the files present in a directory.