SoFunction
Updated on 2025-03-10

Python practical tips: How to get the suffix name (extension) or file name

1. Introduction

In daily programming, we often need to process files, including reading, writing, moving, copying and other operations. In these operations, getting the file extension (suffix name) or file name is a common requirement. Python provides a variety of methods to achieve this requirement. This article will introduce several methods in detail and deepen understanding through practical cases.

2. Obtain the file name

In Python, getting file names is usually used()function. This function takes a file path as an argument and returns the basic name of the file, that is, the part after the last path separator.

Here is a simple example:

import os

# Define a file pathfile_path = "/home/user/documents/"

# Use() to get file namefile_name = (file_path)

print(file_name)  # Output:

💡Notice()Functions return only file names, not paths or extensions.

3. Get the file extension

In Python, getting file extensions is usually used()function. This functionAccept a file path as an argument and return a tuple where the first element is the base name of the file (excluding the extension) and the second element is the extension of the file (including the dot number)

Here is a simple example:

import os

# Define a file pathfile_path = "/home/user/documents/"

# Use() to get filename and extensionfile_name, file_extension = (file_path)

print("file name:", file_name)  # Output: File name: /home/user/documents/exampleprint("Extension:", file_extension)  # Output: Extension: .txt

💡Notice()The extension returned by the function includes the dot number (.). If you want to remove the dot, you can do it through string slicing operations:

file_extension = file_extension[1:]  # Remove the point numberprint("Remove the extension of the dot:", file_extension)  # Output: Remove the extension of the dot number: txt

4. Practical cases

Now, let's look at a practical case to demonstrate how to use the knowledge of obtaining file names and extensions in actual programming. Suppose we have a folder that contains multiple files. We need to traverse this folder and print out the file name and extension of each file.

import os

# Define a folder pathfolder_path = "/home/user/documents"

# traverse files in foldersfor file_name in (folder_path):
    # Complete path to splicing files    file_path = (folder_path, file_name)
    
    # Determine whether it is a file (exclude folders)    if (file_path):
        # Use() to get filename and extension        file_base_name, file_ext = (file_name)
        
        # Print file name and extension        print(f"file name: {file_base_name}, Extension: {file_ext[1:]}")

This sample code will iterate through all files in the specified folder and print out the file name and extension of each file.

💡Notice:When printing the extension, we used the string slice operation to remove the dot number.

5. Summary

This article introduces several ways to get file names and extensions in Python, including using()Functions get filename and use()Function gets the file name and extension. Through demonstration of practical cases, we learned how to apply this knowledge in actual programming. I hope this article can help you better handle file-related programming tasks!

Attachment: Python gets the list of all specified suffix files under the specified folder

import os
# Get all files with specified suffixes under the specified path# dir Specify path# ext Specify the suffix, the linked list & does not need to be dotted or specified.  Example: ['xml', 'java']def GetFileFromThisRootDirV2(target_dir, target_suffix="pxy"):
    find_res = []
    target_suffix_dot = "." + target_suffix
    walk_generator = (target_dir)
    for root_path, dirs, files in walk_generator:
        if len(files) < 1:
            continue
        for file in files:
            file_name, suffix_name = (file)
            if suffix_name == target_suffix_dot:
                find_res.append((root_path, file))
    return find_res
    
LogList = GetFileFromThisRootDirV2("D:/temp", "log")

This is the article about how to get the suffix name (extension) or file name in Python. For more related Python to get the suffix name or file name, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!