Get filename from path without extension using Python
Getting a filename from Python using a path is a complex process not because of the regex we need to use to separate the filename from the path but because of the different types of separators used in file paths in different operating systems. For example, UNIX-based systems like Linux or Mac Os uses “/” (Forward Slash) as separators of the directory while Windows uses “\” (Back Slash) for separating the directories inside the path. So to avoid all these problems we would use a built-in package in python ntpath and use that to first extract the basename (the name that contains the filename with the extension). Then we could use simple python slicing to find the filename without the extension.
- Firstly we would use the ntpath module. Secondly, we would extract the base name of the file from the path and append it to a separate array. The code for the same goes like this.
- Then we would take the array generated and find the last occurrence of the “.” character in the string. Remember finding only the instance of “.” instead of the last occurrence may create problems if the name of the file itself contains “.”. We would find that index using rfind and then finally slice the part of the string before the index to get the filename. The code looks something like this. Again you can store those filenames in a list and use them elsewhere but here we decided to print them to the screen simply.
Below is the complete program:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course