Python Forum

Full Version: Is there a better way
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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"
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
Pathlib to the rescue!

import pathlib as path

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