0

There are many files in a folder like

sample-file.dat host-111.222.333.444.dat win.2k3.dat hello.micro.world.dat

I was using split

 file = os.path.basename(path) 
filename = file.split(".")[0]

but it does not work for all files, is there a better way to read whole filename even with dots and ignore only .dat extension

3 Answers3

3

Try

if file.endswith('.dat'):
    filename = file[:-4]

file[:-4] means get the string file and remove the last four characters

Alternatively, see this question for more answers: How to replace (or strip) an extension from a filename in Python?

Community
  • 1
  • 1
deadbeef404
  • 623
  • 4
  • 14
3

I would use rfind:

>>> s = "host-111.222.333.444.dat"
>>> filename = s[:s.rfind(".")]
>>> filename
'host-111.222.333.444'

It's like find(), but it returns the highest index.

Hope it helps!

cdonts
  • 9,304
  • 4
  • 46
  • 72
3

if they have multiple points, slice and recombine with join !

file = os.path.basename(path) 
filename = ".".join(file.split(".")[:-1])

This will remove what's after the last point, without checking the content,i.e.

  • a.b.c => a.b
  • a.b.dat => a.b
  • a.exe => a
  • .emacs => error ?
  • a.b.c. => a.b.c
Bruce
  • 7,094
  • 1
  • 25
  • 42