find the name of a file in python

You can find the name of a file in Python using several methods. Here are three common methods:

  1. Using the os module:
main.py
import os

# assuming the file path is stored in a variable called file_path
file_name = os.path.basename(file_path)
print(file_name)
134 chars
6 lines
  1. Using string manipulation:
main.py
# assuming the file path is stored in a variable called file_path
file_name = file_path.split("/")[-1]
print(file_name)
120 chars
4 lines
  1. Using the pathlib module (Python 3.4 and above):
main.py
from pathlib import Path

# assuming the file path is stored in a variable called file_path
file_name = Path(file_path).name
print(file_name)
142 chars
6 lines

All three methods will return the name of the file with its extension.

gistlibby LogSnag