![]() |
|
[Tut] Extract File Name From the Path, No Matter What the os/path Format - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Extract File Name From the Path, No Matter What the os/path Format (/thread-99345.html) |
[Tut] Extract File Name From the Path, No Matter What the os/path Format - xSicKxBot - 05-06-2022 Extract File Name From the Path, No Matter What the os/path Format Summary: Code: os.path.basename(path)Code: ntpathCode: os.path Problem: How to extract the filename from a path, no matter what the operating system or path format is?For example, let’s suppose that you want all the following paths to return Code: demo.pyCode: ➤ C:\Users\SHUBHAM SAYON\Desktop\codes\demo.py
➤ /home/username/Desktop/codes/demo.py
➤ /home/username/Desktop/../demo.pyExpected Output in each case: Code: demo.pyRecommended: How To Get The Filename Without The Extension From A Path In Python? Let us dive into the solutions without further delay. ❖ [b]Method 1: Using os.path.basename[/b] Code: os.path.basenameExample 1: In Windows Code: import os
file_path = r'C:\Users\SHUBHAM SAYON\Desktop\codes\demo.py'
print(os.path.basename(file_path)) # OUTPUT: demo.pyExample 2: In Linux ![]() Caution: If you use the Code: os.path.basename()Code: C:\\my\\file.txtTidbit: Code: os.path.basename()Code: os.path.split()❖ [b]Method 2: Using the ntpath Module[/b] The Code: ntpathCode: os.path.basenameThis is where the Code: ntpathCode: ntpathCode: os.pathIn case the file ends with a slash, then the basename will be empty, so you can make your own function and deal with it: Code: import ntpath def path_foo(path): head, tail = ntpath.split(path) return tail or ntpath.basename(head) paths = [r'C:\Users\SHUBHAM SAYON\Desktop\codes\demo.py', r'/home/username/Desktop/codes/demo.py', r'/home/username/Desktop/../demo.py']
print([path_foo(path) for path in paths]) # ['demo.py', 'demo.py', 'demo.py']If you are using Python 3.4 or above, then the Code: pathlib.Path()Code: from pathlib import Path
file_path = r'C:\Users\SHUBHAM SAYON\Desktop\codes\demo.py'
file_name = Path(file_path).name
print(file_name) # demo.pyNote: The Code: .name Bonus Tip: You can also use Code: Path("File Path").stemExample: Code: from pathlib import Path
file_path = r'C:\Users\SHUBHAM SAYON\Desktop\codes\demo.py'
file_name = Path(file_path).stem
print(file_name) # demoIf you do not intend to use any built-in module to extract the filename irrespective of the OS/platform in use, then you can simply use the Code: split()Example: Code: import os
file_path = r'C:\Users\SHUBHAM SAYON\Desktop\codes\demo.py'
head, tail = os.path.split(file_path)
print(tail) # demo.pyExplanation: In the above example Code: os.path.split()➤ A Quick Recap to split(): Code: split()Learn more about the Code: split()Alternatively, for more accurate results you can also use a combination of the strip() and Code: split()Code: file_path = r'C:\Users\SHUBHAM SAYON\Desktop\codes\demo.py'
f_name = file_path.strip('/').strip('\\').split('/')[-1].split('\\')[-1]
print(f_name)
# demo.pyExplanation: The Code: stripCode: split❖ [b]Method 5: Using Regex[/b] If you have a good grip on regular expressions then here’s a regex specific solution for you that will most probably work on any OS. Code: import re
file_path = r'C:\Users\SHUBHAM SAYON\Desktop\codes\\'
def base_name(path): basename = re.search(r'[^\\/]+(?=[\\/]?$)', path) if basename: return basename.group(0) paths = [r'C:\Users\SHUBHAM SAYON\Desktop\codes\demo.py', r'/home/username/Desktop/codes/demo.py', r'/home/username/Desktop/../demo.py']
print([base_name(path) for path in paths]) # ['demo.py', 'demo.py', 'demo.py']Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video. [b]Conclusion[/b] To sum thungs up, you can use one of the following methods to extract the filename from a given path irrespective of the OS/path format:
Please stay tuned and subscribe for more interesting articles! To become a PyCharm master, check out our full course on the Finxter Computer Science Academy available for free for all Finxter Premium Members:
|