Hướng dẫn how do i see all file extensions in python? - làm cách nào để xem tất cả các phần mở rộng tệp 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)

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::

Hướng dẫn how do i see all file extensions in python? - làm cách nào để xem tất cả các phần mở rộng tệp trong python?
Tiện ích mở rộng tập tin trong Python
  • 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ý

Làm cách nào để kiểm tra các phần mở rộng Python?

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.use Python os module splitext() function to get the file extension. This function splits the file path into a tuple having two values - root and extension.

Làm cách nào để xem phần mở rộng tệp?

Xem phần mở rộng tệp của một tệp..
Nhấp chuột phải vào tệp ..
Chọn tùy chọn Thuộc tính ..
Trong cửa sổ Thuộc tính, tương tự như những gì được hiển thị bên dưới, xem loại mục nhập tệp, là loại tệp và phần mở rộng.Trong ví dụ dưới đây, tệp là một tệp TXT với a.Text Tiện ích mở rộng ..

Làm thế nào để bạn liệt kê tất cả các tệp trong một thư mục với một tiện ích mở rộng nhất định trong Python?

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 hệ điều hành.đi bộ () nếu chúng tôi cũng muốn làm việc với các hướng dẫn 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.

Làm thế nào để bạn kiểm tra xem một tệp là tệp .txt trong python?

Sử dụng mô -đun GLOB, bạn có thể tìm kiếm các tệp với các tiện ích mở rộng nhất định ...
hệ điều hành.CHDIR ("my_dir") đặt thư mục làm việc hiện tại thành /my_dir ..
Sử dụng một vòng lặp For, bạn có thể tìm kiếm các tệp với.TXT Tiện ích mở rộng sử dụng GLOB () ..
* Biểu thị tất cả các tệp với một tiện ích mở rộng nhất định ..