How to get the filename without the extension from a path in Python?

How to get the filename without the extension from a path in Python?

I found out a method called os.path.basename to get the filename with extension. But even when I import os, I am not able to call it path.basename . Is it possible to call it as directly as basename?


Getting the name of the file without the extension :

import os
print(os.path.splitext("path_to_file")[0])

As for your import problem, you solve it this way :

from os.path import basename

# now you can call it directly with basename
print(basename("/a/b/c.txt"))

滚动它:

>>> import os
>>> base=os.path.basename('/root/dir/sub/file.ext')
>>> base
'file.ext'
>>> os.path.splitext(base)
('file', '.ext')
>>> os.path.splitext(base)[0]
'file'

>>> print os.path.splitext(os.path.basename("hemanth.txt"))[0]
hemanth
链接地址: http://www.djcxy.com/p/3378.html

上一篇: Python glob多个文件类型

下一篇: 如何在没有Python中的路径扩展的情况下获取文件名?