Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

Python 获取文件后缀

  1. User

    Python 获取文件后缀

  2. Assistant

    可以使用os.path.splitext()函数来获取文件后缀。该函数将文件名分割成路径名和扩展名两部分,并返回一个元组。

    以下是一个示例代码:

    import os
    
    filename = "example.txt"
    file_ext = os.path.splitext(filename)[1]
    
    print(file_ext)  # 输出:.txt
    

    在这个例子中,变量filename存储了文件名example.txt。通过使用os.path.splitext()函数,我们可以获取文件的扩展名,将其存储在变量file_ext中,并使用print()函数输出。