是否有从文件名中提取扩展名的功能?


当前回答

def NewFileName(fichier):
    cpt = 0
    fic , *ext =  fichier.split('.')
    ext = '.'.join(ext)
    while os.path.isfile(fichier):
        cpt += 1
        fichier = '{0}-({1}).{2}'.format(fic, cpt, ext)
    return fichier

其他回答

name_only=file_name[:filename.index(".")

这将为您提供文件名,最多为第一个“.”,这将是最常见的。

# try this, it works for anything, any length of extension
# e.g www.google.com/downloads/file1.gz.rs -> .gz.rs

import os.path

class LinkChecker:

    @staticmethod
    def get_link_extension(link: str)->str:
        if link is None or link == "":
            return ""
        else:
            paths = os.path.splitext(link)
            ext = paths[1]
            new_link = paths[0]
            if ext != "":
                return LinkChecker.get_link_extension(new_link) + ext
            else:
                return ""

从Python中的文件名提取扩展名

Python os模块splitext()

splitext()函数将文件路径拆分为具有两个值的元组:root和extension。

import os
# unpacking the tuple
file_name, file_extension = os.path.splitext("/Users/Username/abc.txt")
print(file_name)
print(file_extension)

使用Pathlib模块获取文件扩展名

获取文件扩展名的Pathlib模块

import pathlib
pathlib.Path("/Users/pankaj/abc.txt").suffix
#output:'.txt'

您可以使用endswith来识别python中的文件扩展名

如以下示例

for file in os.listdir():
    if file.endswith('.csv'):
        df1 =pd.read_csv(file)
        frames.append(df1)
        result = pd.concat(frames)

如果你喜欢正则表达式,那就是一个真正的单行。即使中间有额外的“.”也无关紧要

import re

file_ext = re.search(r"\.([^.]+)$", filename).group(1)

查看此处查看结果:单击此处