views:

1995

answers:

5

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?

+11  A: 

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")
Geo
Huh? "from os.path import basename as basename" is just the same as "from os.path import basename". The "as ..." is unnecessary, and just adds clutter.
Devin Jeanpierre
Yes, I know. I forgot to add the comments where I explained why I did that.
Geo
There is no reason to do that. It's essentially a no-op-- if you want to illustrate importing it under a new name, actually import it under a new name. import foo as foo is just useless.
Devin Jeanpierre
Sure thing. +1, by the way. You answered the whole question (as did that other guy that I gave +1).
Devin Jeanpierre
+4  A: 

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?

import os, and then use os.path.basename

importing os doesn't mean you can use os.foo without referring to os.

Devin Jeanpierre
though if you wanted to call foo directly you could use `from os import foo`.
tgray
+5  A: 

Just roll it:

>>> base=os.path.basename('/root/dir/sub/file.ext')
>>> base
'file.ext'
>>> os.path.splitext(base)
('file', '.ext')
>>> os.path.splitext(base)[0]
'file'
>>>
gimel
+2  A: 
>>> print os.path.splitext(os.path.basename("hemanth.txt"))[0]
hemanth
hemanth.hm
+1 for this. 3 exact same answers, but this is the most direct one. You just could have used ``` for showing the code, and "/somepath/hermanth.txt" as a path instance.
Cawas
Thanks, i added the `` but don really know why the code is not been highlighted!
hemanth.hm
A: 

i want to extract rasmi.tar.gz to rasmi can anyone provime me the solution

Rasmi