Python Forum
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is there a better way
#1
Is there a better way of doing this?

f = open(somename.dat)
print ("{0}" .format(f.name) + ".txt")
output is "somename.dat.txt"

Also want just the file name without the "dat" extension so output will be:

"somename.txt"
Reply
#2
I don't see the point,do you also have file on disk named somename.txt.
Or just want to rename the file?
>>> f = open('somename.dat')
>>> print ('{}.txt'.format(f.name.split('.')[0]))
somename.txt
Reply
#3
Pathlib to the rescue!

import pathlib as path

with open("somefile.txt") as f:
    info = path.Path(f.name)
    print(info.stem) # "somefile"
Reply


Forum Jump:

User Panel Messages

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