Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python get filename
#1
Hi Team,

I want to extract filename without extension. I know below methods
any other way of getting same output.
expected abc

fname = "abc.xlsx"
fname = fname.replace(".xlsx","")
print(fname)


fname = "abc.xlsx"
fname = fname.split(".")[0]
print(fname)
Reply
#2
You could use a Path from pathlib and use the method stem to get the final path component, minus its last suffix.
import pathlib

fname = "abc.xlsx"
path = pathlib.Path(fname)
print(path.stem)
Output:
abc
Reply
#3
If you use pathlib.Path, it would be simply: filename.stem

Example (assume file in in home/documents directory):
>>> from pathlib import Path
>>> 
>>> filename = Path("/home/documents/abc.xlsx")
>>> print(filename.stem)
abc
>>>
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python 2.7 Import error. Directory and filename conflict petcoo00 2 2,398 Feb-02-2020, 08:46 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020