Title: Get a file's directory, name, extension, and other parts in Python
If I need to do something often enough, I sometimes make a post so I can easily look it up later. This is that kind of post.
There are many ways to get the parts of a file name. This one uses the os library. Here's the code.
import os
filename = 'C:/somedir/somesubdir/myfile.ext'
path = os.path.dirname(filename)
basename = os.path.basename(filename) # Full name without path
filetitle = basename.split('.')[0] # Name without path or extension
name, extension = os.path.splitext(filename) # Name with path, extension
print(f'{path = }')
print(f'{basename = }')
print(f'{filetitle = }')
print(f'{name = }')
print(f'{extension = }')
And here's the output.
path = 'C:/somedir/somesubdir'
basename = 'myfile.ext'
filetitle = 'myfile'
name = 'C:/somedir/somesubdir/myfile'
extension = '.ext'
This is pretty self-explanatory. The only note I should make is that the code works if the file doesn't have an extension. For example, with the filename C:/somedir/somesubdir/myfile.ext, the code produces this result:
path = 'C:/somedir/somesubdir'
basename = 'myfile'
filetitle = 'myfile'
name = 'C:/somedir/somesubdir/myfile'
extension = ''
|