是否有从文件名中提取扩展名的功能?
当前回答
对于简单的用例,一个选项可能是从点拆分:
>>> 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
其他回答
另一种右拆分解决方案:
# 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])
如果您想提取最后一个文件扩展名,如果它有多个
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,即使只有一个扩展名也能正常工作
上面的任何解决方案都有效,但在linux上,我发现扩展字符串末尾有一个换行符,这将阻止匹配成功。将strip()方法添加到末尾。例如:
import os.path
extension = os.path.splitext(filename)[1][1:].strip()
只需加入所有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'
这是在一行中同时获取文件名和扩展名的最简单方法。
fName, ext = 'C:/folder name/Flower.jpeg'.split('/')[-1].split('.')
>>> print(fName)
Flower
>>> print(ext)
jpeg
与其他解决方案不同,您不需要为此导入任何包。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录