[Rod Stephens Books]
Index Books Python Examples About Rod Contact
[Mastodon] [Bluesky]
[Build Your Own Ray Tracer With Python]

[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

Title: Get a file's directory, name, extension, and other parts in Python

[A file's directory, name, extension, and other parts]

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 = ''

© 2024 - 2025 Rocky Mountain Computer Consulting, Inc. All rights reserved.