Hướng dẫn get extension file python - lấy tệp 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.

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 get extension file python - lấy tệp mở rộng 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.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up

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.

  • 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.
  • 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.
  • 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.

    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.

    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.

    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ý
    • 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.

    Xem phần mở rộng tệp của một tệp..Using Python os module splittext() function

    Nhấp chuột phải vào tệp ..

    Python3

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

    >>> 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'
    >>> 
    
    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'
    >>> 
    
    5

    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.

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

    >>> 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'
    >>> 
    
    4
    ('my_file', '.txt')
    File Name:  my_file
    File Extension:  .txt
    7
    ('my_file', '.txt')
    File Name:  my_file
    File Extension:  .txt
    8
    ('my_file', '.txt')
    File Name:  my_file
    File Extension:  .txt
    9

    >>> 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'
    >>> 
    
    4
    ('my_file', '.txt')
    File Name:  my_file
    File Extension:  .txt
    7
    File Extension:  .txt
    2
    File Extension:  .txt
    3

    Output:

    ('my_file', '.txt')
    File Name:  my_file
    File Extension:  .txt

    hệ điều hành.CHDIR ("my_dir") đặt thư mục làm việc hiện tại thành /my_dir ..Using Pathlib module

    The pathlib.Path().suffix method of the Pathlib module can be used to extract the extension of the file path. This method is preferred for an object-oriented approach.

    Python3

    import

    File Extension:  .txt
    5

    ('my_file', '.txt')
    File Name:  my_file
    File Extension:  .txt
    1
    >>> 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'
    >>> 
    
    0
    File Extension:  .txt
    8
    >>> 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'
    >>> 
    
    2
    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)
    
    0

    >>> 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'
    >>> 
    
    4
    ('my_file', '.txt')
    File Name:  my_file
    File Extension:  .txt
    7
    File Extension:  .txt
    2
    File Extension:  .txt
    3

    Output:

    File Extension:  .txt

    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.

    Nội dung chính ShowShow

    • 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.
    • Nội dung chính Show
    • Sự kết luận
    • Muốn tìm hiểu thêm? Tham gia cộng đồng DigitalOcean!
    • Làm cách nào để kiểm tra các phần mở rộng Python?
    • Làm cách nào để xem phần mở rộng tệp?
    • 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?
    • 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 ...

    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)
    

    hệ điều hành.CHDIR ("my_dir") đặt thư mục làm việc hiện tại thành /my_dir ..

    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.

    Nội dung chính Show

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

    Nhận phần mở rộng tệp trong Python
    • Nhận tiện ích mở rộng tệp bằng mô -đun Pathlib
    • 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.
    • 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.

    Nội dung chính Show

    Nhận phần mở rộng tệp trong Python

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