是否有从文件名中提取扩展名的功能?
当前回答
如果您想提取最后一个文件扩展名,如果它有多个
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,即使只有一个扩展名也能正常工作
其他回答
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
import os.path
extension = os.path.splitext(filename)[1][1:]
只获取扩展名的文本,而不获取点。
最简单的获取方法是使用mimtypes,下面是示例:
import mimetypes
mt = mimetypes.guess_type("file name")
file_extension = mt[0]
print(file_extension)
虽然这是一个古老的话题,但我想知道为什么在本例中没有提到一个非常简单的python api rpartition:
要获取给定文件绝对路径的扩展名,只需键入:
filepath.rpartition('.')[-1]
例子:
path = '/home/jersey/remote/data/test.csv'
print path.rpartition('.')[-1]
将给您:“csv”
值得在那里加一个较低的,这样你就不会发现自己为什么JPG没有出现在你的列表中。
os.path.splitext(filename)[1][1:].strip().lower()
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录