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

发布于 2024-07-13 09:21:10 字数 24 浏览 8 评论 0原文

有没有从文件名中提取扩展名的函数?

Is there a function to extract the extension from a filename?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

中二柚 2024-07-20 09:21:10

使用 os.path.splitext

>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'

与大多数手动字符串分割尝试不同,os.path.splitext 会正确地将 /a/bc/d 视为没有扩展名,而不是具有扩展名 < code>.c/d,它会将 .bashrc 视为没有扩展名,而不是具有扩展名 .bashrc

>>> os.path.splitext('/a/b.c/d')
('/a/b.c/d', '')
>>> os.path.splitext('.bashrc')
('.bashrc', '')

Use os.path.splitext:

>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'

Unlike most manual string-splitting attempts, os.path.splitext will correctly treat /a/b.c/d as having no extension instead of having extension .c/d, and it will treat .bashrc as having no extension instead of having extension .bashrc:

>>> os.path.splitext('/a/b.c/d')
('/a/b.c/d', '')
>>> os.path.splitext('.bashrc')
('.bashrc', '')
人心善变 2024-07-20 09:21:10

3.4 版中的新功能。

import pathlib

print(pathlib.Path('yourPath.example').suffix) # '.example'
print(pathlib.Path("hello/foo.bar.tar.gz").suffixes) # ['.bar', '.tar', '.gz']
print(pathlib.Path('/foo/bar.txt').stem) # 'bar'

我很惊讶没有人提到< code>pathlib 然而,pathlib 太棒了!

New in version 3.4.

import pathlib

print(pathlib.Path('yourPath.example').suffix) # '.example'
print(pathlib.Path("hello/foo.bar.tar.gz").suffixes) # ['.bar', '.tar', '.gz']
print(pathlib.Path('/foo/bar.txt').stem) # 'bar'

I'm surprised no one has mentioned pathlib yet, pathlib IS awesome!

太阳公公是暖光 2024-07-20 09:21:10
import os.path
extension = os.path.splitext(filename)[1]
import os.path
extension = os.path.splitext(filename)[1]
慈悲佛祖 2024-07-20 09:21:10
import os.path
extension = os.path.splitext(filename)[1][1:]

仅获取扩展名的文本,不带点。

import os.path
extension = os.path.splitext(filename)[1][1:]

To get only the text of the extension, without the dot.

臻嫒无言 2024-07-20 09:21:10

对于简单的用例,一个选项可能会从点中分离出来:

>>> filename = "example.jpeg"
>>> filename.split(".")[-1]
'jpeg'

当文件没有扩展名时不会出错:

>>> "filename".split(".")[-1]
'filename'

但你必须小心:

>>> "png".split(".")[-1]
'png'    # But file doesn't have an extension

也不适用于 Unix 系统中的隐藏文件:

>>> ".bashrc".split(".")[-1]
'bashrc'    # But this is not an extension

对于一般用途,更喜欢 os.path.splitext

For simple use cases one option may be splitting from dot:

>>> filename = "example.jpeg"
>>> filename.split(".")[-1]
'jpeg'

No error when file doesn't have an extension:

>>> "filename".split(".")[-1]
'filename'

But you must be careful:

>>> "png".split(".")[-1]
'png'    # But file doesn't have an extension

Also will not work with hidden files in Unix systems:

>>> ".bashrc".split(".")[-1]
'bashrc'    # But this is not an extension

For general use, prefer os.path.splitext

是伱的 2024-07-20 09:21:10

值得在其中添加一个较低的值,这样您就不会发现自己想知道为什么 JPG 没有出现在您的列表中。

os.path.splitext(filename)[1][1:].strip().lower()

worth adding a lower in there so you don't find yourself wondering why the JPG's aren't showing up in your list.

os.path.splitext(filename)[1][1:].strip().lower()
抱猫软卧 2024-07-20 09:21:10

上述任何解决方案都有效,但在 Linux 上我发现扩展字符串末尾有一个换行符,这将阻止匹配成功。 将 strip() 方法添加到末尾。 例如:

import os.path
extension = os.path.splitext(filename)[1][1:].strip() 

Any of the solutions above work, but on linux I have found that there is a newline at the end of the extension string which will prevent matches from succeeding. Add the strip() method to the end. For example:

import os.path
extension = os.path.splitext(filename)[1][1:].strip() 
御弟哥哥 2024-07-20 09:21:10

使用 splitext 时,具有双扩展名的文件会出现问题(例如 file.tar.gzfile.tar.bz2 等),

>>> fileName, fileExtension = os.path.splitext('/path/to/somefile.tar.gz')
>>> fileExtension 
'.gz'

但应该是:。 tar.gz

可能的解决方案在此处

With splitext there are problems with files with double extension (e.g. file.tar.gz, file.tar.bz2, etc..)

>>> fileName, fileExtension = os.path.splitext('/path/to/somefile.tar.gz')
>>> fileExtension 
'.gz'

but should be: .tar.gz

The possible solutions are here

仅一夜美梦 2024-07-20 09:21:10

您可以在 pathlib 模块(在 python 3.x 中可用)中找到一些很棒的东西。

import pathlib
x = pathlib.PurePosixPath("C:\\Path\\To\\File\\myfile.txt").suffix
print(x)

# Output 
'.txt'

You can find some great stuff in pathlib module (available in python 3.x).

import pathlib
x = pathlib.PurePosixPath("C:\\Path\\To\\File\\myfile.txt").suffix
print(x)

# Output 
'.txt'
赴月观长安 2024-07-20 09:21:10

只需加入所有pathlib后缀即可。

>>> x = 'file/path/archive.tar.gz'
>>> y = 'file/path/text.txt'
>>> ''.join(pathlib.Path(x).suffixes)
'.tar.gz'
>>> ''.join(pathlib.Path(y).suffixes)
'.txt'

Just join all pathlib suffixes.

>>> x = 'file/path/archive.tar.gz'
>>> y = 'file/path/text.txt'
>>> ''.join(pathlib.Path(x).suffixes)
'.tar.gz'
>>> ''.join(pathlib.Path(y).suffixes)
'.txt'
守望孤独 2024-07-20 09:21:10

虽然这是一个老话题,但我想知道为什么没有人提到一个非常简单的 python api,称为 rpartition 在这种情况下:

要获得给定文件绝对路径的扩展名,您可以简单地输入:

filepath.rpartition('.')[-1]

example:

path = '/home/jersey/remote/data/test.csv'
print path.rpartition('.')[-1]

will get you: 'csv '

Although it is an old topic, but i wonder why there is none mentioning a very simple api of python called rpartition in this case:

to get extension of a given file absolute path, you can simply type:

filepath.rpartition('.')[-1]

example:

path = '/home/jersey/remote/data/test.csv'
print path.rpartition('.')[-1]

will give you: 'csv'

烟花肆意 2024-07-20 09:21:10

令人惊讶的是,还没有提到这一点:

import os
fn = '/some/path/a.tar.gz'

basename = os.path.basename(fn)  # os independent
Out[] a.tar.gz

base = basename.split('.')[0]
Out[] a

ext = '.'.join(basename.split('.')[1:])   # <-- main part

# if you want a leading '.', and if no result `None`:
ext = '.' + ext if ext else None
Out[] .tar.gz

优点:

  • 按我能想到的任何方式工作
  • 没有模块
  • 没有正则表达式
  • 跨平台
  • 易于扩展(例如没有用于扩展的前导点,只有扩展的最后一部分)

作为功能:

def get_extension(filename):
    basename = os.path.basename(filename)  # os independent
    ext = '.'.join(basename.split('.')[1:])
    return '.' + ext if ext else None

Surprised this wasn't mentioned yet:

import os
fn = '/some/path/a.tar.gz'

basename = os.path.basename(fn)  # os independent
Out[] a.tar.gz

base = basename.split('.')[0]
Out[] a

ext = '.'.join(basename.split('.')[1:])   # <-- main part

# if you want a leading '.', and if no result `None`:
ext = '.' + ext if ext else None
Out[] .tar.gz

Benefits:

  • Works as expected for anything I can think of
  • No modules
  • No regex
  • Cross-platform
  • Easily extendible (e.g. no leading dots for extension, only last part of extension)

As function:

def get_extension(filename):
    basename = os.path.basename(filename)  # os independent
    ext = '.'.join(basename.split('.')[1:])
    return '.' + ext if ext else None
静赏你的温柔 2024-07-20 09:21:10

您可以在文件名上使用split

f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))

这不需要额外的库

You can use a split on a filename:

f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))

This does not require additional library

后eg是否自 2024-07-20 09:21:10

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

Python os 模块 splitext()

splitext() 函数将文件路径拆分为具有两个值的元组 - 根和扩展名。

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'

Extracting extension from filename in Python

Python os module splitext()

splitext() function splits the file path into a tuple having two values – root and extension.

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

Get File Extension using Pathlib Module

Pathlib module to get the file extension

import pathlib
pathlib.Path("/Users/pankaj/abc.txt").suffix
#output:'.txt'
晨敛清荷 2024-07-20 09:21:10
filename='ext.tar.gz'
extension = filename[filename.rfind('.'):]
filename='ext.tar.gz'
extension = filename[filename.rfind('.'):]
断念 2024-07-20 09:21:10

即使这个问题已经得到解答,我也会在正则表达式中添加解决方案。

>>> import re
>>> file_suffix = ".*(\..*)"
>>> result = re.search(file_suffix, "somefile.ext")
>>> result.group(1)
'.ext'

Even this question is already answered I'd add the solution in Regex.

>>> import re
>>> file_suffix = ".*(\..*)"
>>> result = re.search(file_suffix, "somefile.ext")
>>> result.group(1)
'.ext'
偏闹i 2024-07-20 09:21:10

这是一种直接的字符串表示技术:
我看到提到了很多解决方案,但我认为大多数都在考虑拆分。
然而,Split 在每次出现“.”时都会执行此操作。 。
您更愿意寻找的是分区。

string = "folder/to_path/filename.ext"
extension = string.rpartition(".")[-1]

This is a direct string representation techniques :
I see a lot of solutions mentioned, but I think most are looking at split.
Split however does it at every occurrence of "." .
What you would rather be looking for is partition.

string = "folder/to_path/filename.ext"
extension = string.rpartition(".")[-1]
南渊 2024-07-20 09:21:10

另一种右分割的解决方案:

# to get extension only

s = 'test.ext'

if '.' in s: ext = s.rsplit('.', 1)[1]

# or, to get file name and extension

def split_filepath(s):
    """
    get filename and extension from filepath 
    filepath -> (filename, extension)
    """
    if not '.' in s: return (s, '')
    r = s.rsplit('.', 1)
    return (r[0], r[1])

Another solution with right split:

# to get extension only

s = 'test.ext'

if '.' in s: ext = s.rsplit('.', 1)[1]

# or, to get file name and extension

def split_filepath(s):
    """
    get filename and extension from filepath 
    filepath -> (filename, extension)
    """
    if not '.' in s: return (s, '')
    r = s.rsplit('.', 1)
    return (r[0], r[1])
若水般的淡然安静女子 2024-07-20 09:21:10

您可以使用以下代码来拆分文件名和扩展名。

    import os.path
    filenamewithext = os.path.basename(filepath)
    filename, ext = os.path.splitext(filenamewithext)
    #print file name
    print(filename)
    #print file extension
    print(ext)

you can use following code to split file name and extension.

    import os.path
    filenamewithext = os.path.basename(filepath)
    filename, ext = os.path.splitext(filenamewithext)
    #print file name
    print(filename)
    #print file extension
    print(ext)
谢绝鈎搭 2024-07-20 09:21:10

好吧,我知道我迟到了,

这是我的简单解决方案

file = '/foo/bar/whatever.ext'
extension = file.split('.')[-1]
print(extension)

#output will be ext

Well , i know im late

that's my simple solution

file = '/foo/bar/whatever.ext'
extension = file.split('.')[-1]
print(extension)

#output will be ext
话少心凉 2024-07-20 09:21:10

如果您喜欢正则表达式,那么这就是真正的一句台词。
即使你有额外的“。”也没关系。 在中间

import re

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

查看结果:单击此处

A true one-liner, if you like regex.
And it doesn't matter even if you have additional "." in the middle

import re

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

See here for the result: Click Here

抱猫软卧 2024-07-20 09:21:10

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

如下例所示

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

You can use endswith to identify the file extension in python

like bellow example

for file in os.listdir():
    if file.endswith('.csv'):
        df1 =pd.read_csv(file)
        frames.append(df1)
        result = pd.concat(frames)
方觉久 2024-07-20 09:21:10

试试这个:

files = ['file.jpeg','file.tar.gz','file.png','file.foo.bar','file.etc']
pen_ext = ['foo', 'tar', 'bar', 'etc']

for file in files: #1
    if (file.split(".")[-2] in pen_ext): #2
        ext =  file.split(".")[-2]+"."+file.split(".")[-1]#3
    else:
        ext = file.split(".")[-1] #4
    print (ext) #5
  1. 获取列表
  2. 分割文件名中的所有文件名并检查倒数第二个扩展名,它是否在 pen_ext 列表中?
  3. 如果是,则将其与最后一个扩展名连接起来,并将其设置为文件的扩展名;
  4. 如果不是,则将最后一个扩展名作为文件的扩展名
  5. ,然后检查出来

try this:

files = ['file.jpeg','file.tar.gz','file.png','file.foo.bar','file.etc']
pen_ext = ['foo', 'tar', 'bar', 'etc']

for file in files: #1
    if (file.split(".")[-2] in pen_ext): #2
        ext =  file.split(".")[-2]+"."+file.split(".")[-1]#3
    else:
        ext = file.split(".")[-1] #4
    print (ext) #5
  1. get all file name inside the list
  2. splitting file name and check the penultimate extension, is it in the pen_ext list or not?
  3. if yes then join it with the last extension and set it as the file's extension
  4. if not then just put the last extension as the file's extension
  5. and then check it out
窝囊感情。 2024-07-20 09:21:10

最简单的获取方法是使用mimtypes,下面是示例:

import mimetypes

mt = mimetypes.guess_type("file name")
file_extension =  mt[0]
print(file_extension)

The easiest way to get is to use mimtypes, below is the example:

import mimetypes

mt = mimetypes.guess_type("file name")
file_extension =  mt[0]
print(file_extension)
烟织青萝梦 2024-07-20 09:21:10

我肯定迟到了,但万一有人想在不使用另一个库的情况下实现这一目标:

file_path = "example_tar.tar.gz"
file_name, file_ext = [file_path if "." not in file_path else file_path.split(".")[0], "" if "." not in file_path else file_path[file_path.find(".") + 1:]]
print(file_name, file_ext)

第二行基本上只是以下代码,但塞进一行:

def name_and_ext(file_path):
    if "." not in file_path:
        file_name = file_path
    else:
        file_name = file_path.split(".")[0]
    if "." not in file_path:
        file_ext = ""
    else:
        file_ext = file_path[file_path.find(".") + 1:]
    return [file_name, file_ext]

即使这有效,它也可能不起作用文件类型,特别是 .zshrc,我建议使用 osos.path.splitext 函数,示例如下:

import os
file_path = "example.tar.gz"
file_name, file_ext = os.path.splitext(file_path)
print(file_name, file_ext)

干杯 :)

I'm definitely late to the party, but in case anyone wanted to achieve this without the use of another library:

file_path = "example_tar.tar.gz"
file_name, file_ext = [file_path if "." not in file_path else file_path.split(".")[0], "" if "." not in file_path else file_path[file_path.find(".") + 1:]]
print(file_name, file_ext)

The 2nd line is basically just the following code but crammed into one line:

def name_and_ext(file_path):
    if "." not in file_path:
        file_name = file_path
    else:
        file_name = file_path.split(".")[0]
    if "." not in file_path:
        file_ext = ""
    else:
        file_ext = file_path[file_path.find(".") + 1:]
    return [file_name, file_ext]

Even though this works, it might not work will all types of files, specifically .zshrc, I would recomment using os's os.path.splitext function, example below:

import os
file_path = "example.tar.gz"
file_name, file_ext = os.path.splitext(file_path)
print(file_name, file_ext)

Cheers :)

很糊涂小朋友 2024-07-20 09:21:10

对于有趣的人来说......只需将扩展名收集在字典中,然后在文件夹中跟踪所有扩展名即可。 然后只需拉出你想要的扩展即可。

import os

search = {}

for f in os.listdir(os.getcwd()):
    fn, fe = os.path.splitext(f)
    try:
        search[fe].append(f)
    except:
        search[fe]=[f,]

extensions = ('.png','.jpg')
for ex in extensions:
    found = search.get(ex,'')
    if found:
        print(found)

For funsies... just collect the extensions in a dict, and track all of them in a folder. Then just pull the extensions you want.

import os

search = {}

for f in os.listdir(os.getcwd()):
    fn, fe = os.path.splitext(f)
    try:
        search[fe].append(f)
    except:
        search[fe]=[f,]

extensions = ('.png','.jpg')
for ex in extensions:
    found = search.get(ex,'')
    if found:
        print(found)
彩虹直至黑白 2024-07-20 09:21:10

此方法需要字典、列表或集合。 您可以使用内置字符串方法来使用“.endswith”。 这将在文件末尾的列表中搜索名称,只需使用 str.endswith(fileName[index]) 即可完成。 这更多的是为了获取和比较扩展。

https://docs.python.org/3/library/stdtypes。 html#string-methods

示例 1:

dictonary = {0:".tar.gz", 1:".txt", 2:".exe", 3:".js", 4:".java", 5:".python", 6:".ruby",7:".c", 8:".bash", 9:".ps1", 10:".html", 11:".html5", 12:".css", 13:".json", 14:".abc"} 
for x in dictonary.values():
    str = "file" + x
    str.endswith(x, str.index("."), len(str))

示例 2:

set1 = {".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"}
for x in set1:
   str = "file" + x
   str.endswith(x, str.index("."), len(str))

示例 3:

fileName = [".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"];
for x in range(0, len(fileName)):
    str = "file" + fileName[x]
    str.endswith(fileName[x], str.index("."), len(str))

示例 4

fileName = [".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"];
str = "file.txt"
str.endswith(fileName[1], str.index("."), len(str))

带有输出的示例 5、6、7
输入图片此处描述

示例 8

fileName = [".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"];
exts = []
str = "file.txt"
for x in range(0, len(x)):
    if str.endswith(fileName[1]) == 1:
         exts += [x]
     

This method will require a dictonary, list, or set. you can just use ".endswith" using built in string methods. This will search for name in list at end of file and can be done with just str.endswith(fileName[index]). This is more for getting and comparing extensions.

https://docs.python.org/3/library/stdtypes.html#string-methods

Example 1:

dictonary = {0:".tar.gz", 1:".txt", 2:".exe", 3:".js", 4:".java", 5:".python", 6:".ruby",7:".c", 8:".bash", 9:".ps1", 10:".html", 11:".html5", 12:".css", 13:".json", 14:".abc"} 
for x in dictonary.values():
    str = "file" + x
    str.endswith(x, str.index("."), len(str))

Example 2:

set1 = {".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"}
for x in set1:
   str = "file" + x
   str.endswith(x, str.index("."), len(str))

Example 3:

fileName = [".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"];
for x in range(0, len(fileName)):
    str = "file" + fileName[x]
    str.endswith(fileName[x], str.index("."), len(str))

Example 4

fileName = [".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"];
str = "file.txt"
str.endswith(fileName[1], str.index("."), len(str))

Examples 5, 6, 7 with output
enter image description here

Example 8

fileName = [".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"];
exts = []
str = "file.txt"
for x in range(0, len(x)):
    if str.endswith(fileName[1]) == 1:
         exts += [x]
     
醉生梦死 2024-07-20 09:21:10

在这里,如果您想提取最后一个文件扩展名(如果它有多个

class functions:
    def listdir(self, filepath):
        return os.listdir(filepath)
    
func = functions()

os.chdir("C:\\Users\Asus-pc\Downloads") #absolute path, change this to your directory
current_dir = os.getcwd()

for i in range(len(func.listdir(current_dir))): #i is set to numbers of files and directories on path directory
    if os.path.isfile((func.listdir(current_dir))[i]): #check if it is a file
        fileName = func.listdir(current_dir)[i] #put the current filename into a variable
        rev_fileName = fileName[::-1] #reverse the filename
        currentFileExtension = rev_fileName[:rev_fileName.index('.')][::-1] #extract from beginning until before .
        print(currentFileExtension) #output can be mp3,pdf,ini,exe, depends on the file on your absolute directory

输出为 mp3),即使只有 1 个扩展名也有效

Here if you want to extract the last file extension if it has multiple

class functions:
    def listdir(self, filepath):
        return os.listdir(filepath)
    
func = functions()

os.chdir("C:\\Users\Asus-pc\Downloads") #absolute path, change this to your directory
current_dir = os.getcwd()

for i in range(len(func.listdir(current_dir))): #i is set to numbers of files and directories on path directory
    if os.path.isfile((func.listdir(current_dir))[i]): #check if it is a file
        fileName = func.listdir(current_dir)[i] #put the current filename into a variable
        rev_fileName = fileName[::-1] #reverse the filename
        currentFileExtension = rev_fileName[:rev_fileName.index('.')][::-1] #extract from beginning until before .
        print(currentFileExtension) #output can be mp3,pdf,ini,exe, depends on the file on your absolute directory

Output is mp3, even works if has only 1 extension name

时光暖心i 2024-07-20 09:21:10
# 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 ""
# 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 ""
仲春光 2024-07-20 09:21:10
a = ".bashrc"
b = "text.txt"
extension_a = a.split(".")
extension_b = b.split(".")
print(extension_a[-1])  # bashrc
print(extension_b[-1])  # txt
a = ".bashrc"
b = "text.txt"
extension_a = a.split(".")
extension_b = b.split(".")
print(extension_a[-1])  # bashrc
print(extension_b[-1])  # txt
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文