Hướng dẫn find file in folder python - tìm 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

    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:

    Ví dụ 1: Nhận tất cả các tệp danh sách trong một thư mụcTo get all the files, and no folders.

    Python3

    Python

    print("Python Program to print list the files in a directory.")

    Ví dụ 2: Để có được tất cả các tệp và không có thư mục.

    printimport4import5)

    import os

    Direc = inputimport0import1

    print(print5print6=print8)

    import7= import9To get only .txt files.

    Python3

    Python

    Ví dụ 2: Để có được tất cả các tệp và không có thư mục.

    import os

    "Python Program to print list the files in a directory."1print"Python Program to print list the files in a directory."3

     Output:Output:

    • Direc = inputimport0import1OS.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.

    import7= import9os.walk(top, topdown, onerror, followlinks)

    • import7= It is the top directory from which you want to retrieve the names of the component files and folders.
    • Ví dụ 2.5: Để chỉ nhận các tệp .txt. 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.
    • os3 (3os5 (5 It provides an error handler if an error is encountered 
    • (6os7 (8(9"Python Program to print list the files in a directory."0: if set to True, visits folders referenced by system links 

    & 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. returns the name of every file and folder within a directory and any of its subdirectories.

    Python3

    Output:

    • & nbsp; os.scandir () được hỗ trợ cho Python 3.5 và Greater. & NBSP; is supported for Python 3.5 and greater. 

    Cú pháp: OS.Scandir (đường dẫn = ‘.os.scandir(path = ‘.’)

    Loại trả về: Trả về một trình lặp của đối tượng OS.DirEntry. returns an iterator of os.DirEntry object.

    Python3

    import os

    "Python Program to print list the files in a directory."6= "Python Program to print list the files in a directory."8

    print()1 )2 )3

    os3 )5os5 )7

    (6os7 Direc 0Direc 1 Direc 2

    "Python Program to print list the files in a directory."1printDirec 5

    Output:

    Phương pháp 2: Sử dụng mô -đun GLOB & NBSP;

    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. & NBSP;glob module is used to retrieve files/path names matching a specified pattern. 

    • Phương thức GLOB (): Với GLOB, chúng ta có thể sử dụng thẻ hoang dã (Hồi*,?, [Phạm vi]) để làm cho việc truy xuất đường dẫn đơn giản và thuận tiện hơn.With glob, we can use wild cards (“*, ?, [ranges])to make path retrieval more simple and convenient.

    Example:

    Python3

    import Direc 7

    Direc 8= =0

    print(=3)

    os3 import7os5 =8os9 input0"Python Program to print list the files in a directory."0

    (6printinput4

    print(input7)

    os3 import7os5 =8os9

    (6printinput4

    print(import11)

    os3 import7os5 =8os9 import18"Python Program to print list the files in a directory."0

    (6printinput4

    Output:

    • & nbsp; iglob () Phương thức có thể được sử dụng để in các tên tệp đệ quy nếu tham số đệ quy được đặt thành true.method can be used to print filenames recursively if the recursive parameter is set to True.

    Cú pháp: glob.iglob (pathName, *, recursive = false)glob.iglob(pathname, *, recursive=False)

    Example:

    Python3

    import Direc 7

    Direc 8= =0

    os3 import7os5 =8os9 input0"Python Program to print list the files in a directory."0

    os3 import7os5 =8os9

    (6print(import33)

    Output:


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

    Python có thể tìm kiếm tên tệp trong một đường dẫn được chỉ định của HĐH. Điều này có thể được thực hiện bằng cách sử dụng HĐH mô -đun với các chức năng đi bộ (). Điều này sẽ lấy một đường dẫn cụ thể làm đầu vào và tạo ra 3-tuple liên quan đến dirpath, dirnames và tên tệp.using the module os with the walk() functions. This will take a specific path as input and generate a 3-tuple involving dirpath, dirnames, and filenames.

    Làm cách nào để xác định một tệp trong Python?

    Python kiểm tra nếu tập tin tồn tại..
    Từ Nhập Os.Path tồn tại File_Exists = tồn tại (PATH_TO_FILE) ....
    từ đường dẫn nhập pathlib path = path (path_to_file) path.is_file () ....
    Nhập OS.Path.....
    OS.Path.exists (path_to_file) ....
    Nhập OS.Path File_Exists = Os.Path.exists ('ReadMe.TXT') in (File_Exists) ....
    False..

    Làm thế nào để bạn tìm thấy các thư mục con trong Python?

    Để có được một danh sách tất cả các thư mục con trong một thư mục, theo cách đệ quy, bạn có thể sử dụng chức năng OS.WALK.Nó trả về ba tuple với mục đầu tiên là tất cả các thư mục con.Bạn cũng có thể liệt kê các thư mục (chỉ ngay lập tức) bằng hệ điều hành.use the os. walk function. It returns a three tuple with first entry being all the subdirectories. You can also list the directories(immediate only) using the os.

    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.

    Chủ đề