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
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 only .txt files.
Python3
Python
Ví dụ 2: Chỉ nhận các tệp .txt.
import
os
import
2import
3import
4
Output:Output:
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[
import
0import
1os.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:
- 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[
import
0import
1
import
2import
3for
6
Output:
& 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;
import
3os
1x
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ó.
import
3os
1in
8x
5
& nbsp; os.scandir [] được hỗ trợ cho Python 3.5 và Greater. & NBSP;
import
3in
5
import
3os
1
2x
5
Cú pháp: OS.Scandir [đường dẫn = ‘.
import
3in
5
Output:
- 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.
import
7import
8import
9glob.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;
import
3os
1x.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;
import
3os
1x.endswith[
4x
5
Output: