Hướng dẫn find all file in folder python - tìm tất cả tệp trong thư mục 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)

Xem thảo luận

Cải thiện bài viết

Lưu bài viết

  • Đọc
  • Bàn luận
  • Xem thảo luận

    Cải thiện bài viết

    Lưu bài viết

    Đọchow do we list all files in a directory in python.

    Bàn luận

    Trong bài viết này, chúng tôi sẽ đề cập đến cách chúng tôi liệt kê tất cả các tệp trong một thư mục trong Python.

    Thư mục là gì? gfg

    Hướng dẫn find all file in folder python - tìm tất cả tệp trong thư mục python

    Một thư mục đôi khi cũng được gọi là thư mục là cấu trúc tổ chức đơn vị trong hệ thống tệp máy tính để lưu trữ và định vị các tệp hoặc nhiều thư mục hơn. Python hiện hỗ trợ một số API để liệt kê nội dung thư mục. Chẳng hạn, chúng ta có thể sử dụng path.iterdir, os.scandir, os.walk, path.rglob hoặc os.listdir hàm. & Nbsp;

    • Thư mục đang sử dụng: GFGos.listdir() method gets the list of all files and directories in a specified directory. By default, it is the current directory. Beyond the first level of folders, os.listdir() does not return any files or folders.

    Phương pháp 1: Mô -đun HĐH: os.listdir(path)

    Parameters::

    • & NBSP; Phương thức Os.ListDir () có được danh sách tất cả các tệp và thư mục trong một thư mục được chỉ định. Theo mặc định, nó là thư mục hiện tại. Ngoài cấp độ đầu tiên của các thư mục, Os.ListDir () không trả về bất kỳ tệp hoặc thư mục nào.

    Cú pháp: Os.ListDir (Path): returns a list of all files and directories in the specified path

    Đường dẫn của thư mục Get all the list files in a Directory

    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

    Output:

    Hướng dẫn find all file in folder python - tìm tất cả tệp trong thư mục python

    Ví dụ 1: Nhận tất cả các tệp danh sách trong một thư mụcTo get only .txt files.

    Python3

    Python

    Ví dụ 2: Chỉ nhận các tệp .txt.

    import os

    import2import3import4

     Output:Output:

    Hướng dẫn find all file in folder python - tìm tất cả tệp trong thư mục python

    • for x in os.listdir():OS.walk() generates file names in a directory tree. This function returns a list of files in a tree structure. The method loops through all of the directories in a tree.

        if x.endswith(import0import1os.walk(top, topdown, onerror, followlinks)

    • & nbsp; os.walk () tạo tên tệp trong một cây thư mục. Hàm này trả về một danh sách các tệp trong cấu trúc cây. Phương pháp lặp qua tất cả các thư mục trong một cái cây. It is the top directory from which you want to retrieve the names of the component files and folders.
    • Cú pháp: OS.WALK (TOP, TOPDOWN, ONEERROR, SAU NGÀY) Specifies that directories should be scanned from the top down when set to True. If this parameter is False, directories will be examined from the top down.
    • Top: Đây là thư mục hàng đầu mà bạn muốn truy xuất tên của các tệp và thư mục thành phần. It provides an error handler if an error is encountered 
    • TOPDOWN: Chỉ định rằng các thư mục nên được quét từ trên xuống khi được đặt thành true. Nếu tham số này là sai, các thư mục sẽ được kiểm tra từ trên xuống.: if set to True, visits folders referenced by system links 

    OnError: Nó cung cấp một trình xử lý lỗi nếu gặp lỗi & nbsp; returns the name of every file and folder within a directory and any of its subdirectories.

    Python3

    Output:

    Hướng dẫn find all file in folder python - tìm tất cả tệp trong thư mục python

    • Theo dõi: Nếu được đặt thành TRUE, các thư mục truy cập được tham chiếu bởi các liên kết hệ thống & nbsp; is supported for Python 3.5 and greater. 

    Trả về: Trả về tên của mỗi tệp và thư mục trong một thư mục và bất kỳ thư mục con nào của nó.os.scandir(path = ‘.’)

    & nbsp; os.scandir () được hỗ trợ cho Python 3.5 và Greater. & NBSP; returns an iterator of os.DirEntry object.

    Python3

    Python

    Ví dụ 2: Chỉ nhận các tệp .txt.

    import os

    for x in os.listdir():

        if x.endswith(import0import1

    import2import3for6

    Output:

    Hướng dẫn find all file in folder python - tìm tất cả tệp trong thư mục python

    & nbsp; os.walk () tạo tên tệp trong một cây thư mục. Hàm này trả về một danh sách các tệp trong cấu trúc cây. Phương pháp lặp qua tất cả các thư mục trong một cái cây.

    Cú pháp: OS.WALK (TOP, TOPDOWN, ONEERROR, SAU NGÀY)glob module is used to retrieve files/path names matching a specified pattern. 

    • Top: Đây là thư mục hàng đầu mà bạn muốn truy xuất tên của các tệp và thư mục thành phần.With glob, we can use wild cards (“*, ?, [ranges])to make path retrieval more simple and convenient.

    Example:

    Python3

    TOPDOWN: Chỉ định rằng các thư mục nên được quét từ trên xuống khi được đặt thành true. Nếu tham số này là sai, các thư mục sẽ được kiểm tra từ trên xuống.

    OnError: Nó cung cấp một trình xử lý lỗi nếu gặp lỗi & nbsp;

    import3os1x 4x 5

    Theo dõi: Nếu được đặt thành TRUE, các thư mục truy cập được tham chiếu bởi các liên kết hệ thống & nbsp;

    Trả về: Trả về tên của mỗi tệp và thư mục trong một thư mục và bất kỳ thư mục con nào của nó.

    import3os1in8x 5

    & nbsp; os.scandir () được hỗ trợ cho Python 3.5 và Greater. & NBSP;

        import3in5

    import3os1    2x 5

    Cú pháp: OS.Scandir (đường dẫn = ‘.

        import3in5

    Output:

    Hướng dẫn find all file in folder python - tìm tất cả tệp trong thư mục python

    • Loại trả về: Trả về một trình lặp của đối tượng OS.DirEntry.method can be used to print filenames recursively if the recursive parameter is set to True.

    import7import8 import9glob.iglob(pathname, *, recursive=False)

    Example:

    Python3

    TOPDOWN: Chỉ định rằng các thư mục nên được quét từ trên xuống khi được đặt thành true. Nếu tham số này là sai, các thư mục sẽ được kiểm tra từ trên xuống.

    OnError: Nó cung cấp một trình xử lý lỗi nếu gặp lỗi & nbsp;

    import3os1x.endswith(1x 5

    Theo dõi: Nếu được đặt thành TRUE, các thư mục truy cập được tham chiếu bởi các liên kết hệ thống & nbsp;

        import3os1x.endswith(4x 5

    Output:

    Hướng dẫn find all file in folder python - tìm tất cả tệp trong thư mục python


    Làm cách nào để tìm kiếm tất cả các tệp trong một thư mục trong Python?

    Để có được danh sách tất cả các tệp và thư mục trong một thư mục cụ thể trong hệ thống tệp, hãy sử dụng os.listdir () trong các phiên bản cũ của python hoặc os.scandir () trong python 3.use os. listdir() in legacy versions of Python or os. scandir() in Python 3.

    Làm thế nào tôi có thể nhận được một danh sách các tệp trong một thư mục?

    Nhấn và giữ phím Shift và sau đó nhấp chuột phải vào thư mục chứa các tệp bạn cần được liệt kê.Nhấp vào Mở cửa sổ lệnh ở đây trên menu mới.Một cửa sổ mới với văn bản màu trắng trên nền đen sẽ xuất hiện.o Bên trái của con trỏ nhấp nháy, bạn sẽ thấy đường dẫn thư mục bạn đã chọn trong bước trước.. Click Open command window here on the new menu. A new window with white text on a black background should appear. o To the left of the blinking cursor you will see the folder path you selected in the previous step.

    Làm cách nào để có được một danh sách các tệp trong Python?

    Sử dụng mô -đun OS Module Python của mô -đun OS cung cấp một chức năng nhận được danh sách các tệp hoặc thư mục trong thư mục.Các ., được thông qua như một lập luận cho OS.listDir (), biểu thị thư mục hiện tại.mảng = hệ điều hành.

    Làm cách nào để in tất cả các tệp trong một thư mục trong Python?

    Đối với bài viết này, các phương pháp sau từ mô -đun HĐH sẽ được yêu cầu:..
    hệ điều hành.StartFile (): Phương thức này in nội dung của một tệp đã cho.Cú pháp: Os.StartFile (đường dẫn, hoạt động = 'mở') ....
    hệ điều hành.ListDir (): Phương thức này liệt kê tất cả các tệp và thư mục trong một thư mục nhất định.....
    hệ điều hành.đường dẫn..