Python Program to Get the File Name From the File Path


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

A file is a unit of information stored on a computer system. It can contain text, images, videos, or any other type of data.

A file name is the name given to a file that identifies it uniquely in the file system. It is usually composed of a name and an extension separated by a dot (e.g., “mytextfile.txt”). The extension is used to indicate the type of the file and is usually used by the operating system to determine which application to use to open the file.

A file path is the location of a file within the file system. It shows the hierarchy of directories or folders that the file is contained within, starting from the root directory of the file system. The file path can be either absolute or relative. An absolute file path specifies the entire path starting from the root directory, while a relative file path specifies the path relative to the current directory.


Python Code :

The below Python program gets the file name from a file path:


# Define a file path
file_path = "/path/to/my/file.txt"

# Split the file path using the "/" separator
path_components = file_path.split("/")

# Get the last component of the path (the file name) using indexing
file_name = path_components[-1]

# Print the file name
print("File name:", file_name)

In this program, we first define a file path file_path as a string.

To get the file name from the file path, we first split the path into its component parts using the split() method. We pass the separator character “/” as an argument to the split() method, which splits the path string into a list of strings at each occurrence of the separator character.

We then use indexing to get the last component of the path, which corresponds to the file name. Since Python uses zero-based indexing, we can access the last element of the list using the index -1.

We assign the resulting file name string to a new variable file_name.

Finally, we print the file name using the print() function to demonstrate that we have successfully extracted the file name from the file path.


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co