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]
Chúng ta có thể sử dụng hàm module splitext [] của Python OS để có được phần mở rộng tệp. Hàm này chia đường dẫn tệp thành một tuple có hai giá trị - root và phần mở rộng.
Nhận phần mở rộng tệp trong Python
Dưới đây là một chương trình đơn giản để có được phần mở rộng tệp trong Python.
import os
# unpacking the tuple
file_name, file_extension = os.path.splitext["/Users/pankaj/abc.txt"]
print[file_name]
print[file_extension]
print[os.path.splitext["/Users/pankaj/.bashrc"]]
print[os.path.splitext["/Users/pankaj/a.b/image.png"]]
Output::
- Trong ví dụ đầu tiên, chúng tôi đang giải nén trực tiếp các giá trị tuple cho hai biến.
- Lưu ý rằng tệp .bashrc không có phần mở rộng. Dấu chấm được thêm vào tên tệp để biến nó thành một tệp ẩn.
- Trong ví dụ thứ ba, có một dấu chấm trong tên thư mục.
Nhận tiện ích mở rộng tệp bằng mô -đun Pathlib
Chúng tôi cũng có thể sử dụng mô -đun Pathlib để có phần mở rộng tệp. Mô -đun này đã được giới thiệu trong bản phát hành Python 3.4.
>>> import pathlib
>>> pathlib.Path["/Users/pankaj/abc.txt"].suffix
'.txt'
>>> pathlib.Path["/Users/pankaj/.bashrc"].suffix
''
>>> pathlib.Path["/Users/pankaj/.bashrc"]
PosixPath['/Users/pankaj/.bashrc']
>>> pathlib.Path["/Users/pankaj/a.b/abc.jpg"].suffix
'.jpg'
>>>
Sự kết luận
Nó luôn luôn tốt hơn để sử dụng các phương thức tiêu chuẩn để có được phần mở rộng tệp. Nếu bạn đã sử dụng mô -đun OS, thì hãy sử dụng phương thức splitExt []. Đối với cách tiếp cận hướng đối tượng, sử dụng mô-đun pathlib.
Muốn tìm hiểu thêm? Tham gia cộng đồng DigitalOcean!
Tham gia cộng đồng DigitalOcean của chúng tôi miễn phí hơn một triệu nhà phát triển! Nhận trợ giúp và chia sẻ kiến thức trong phần Câu hỏi & Câu trả lời của chúng tôi, tìm hướng dẫn và công cụ sẽ giúp bạn phát triển như một nhà phát triển và mở rộng quy mô dự án hoặc doanh nghiệp của bạn, và đăng ký các chủ đề quan tâm.
Đăng ký