Python Program to Extract Extension From the File Name
An extension of a file is a suffix at the end of the file name that tells the operating system and other programs what type of file it is and how it should be handled. It usually consists of a period (.) followed by a few letters or numbers.
For example, in the file name “example.txt”, the extension is “.txt”, which indicates that it is a plain text file. Some common file extensions include .docx for Microsoft Word documents, .jpg for image files, .mp3 for audio files, .pdf for documents in Portable Document Format, and .html for web pages.
Python Code :
The below Python program extracts the extension from a file name:
# Define the file name filename = "example.txt" # Use the split() method to split the file name into a list name_parts = filename.split(".") # Extract the last element of the list as the extension extension = name_parts[-1] # Print the extension to confirm that it was extracted correctly print(extension)
In this program, we first define the file name that we want to extract the extension from by assigning it to the variable filename.
We then use the split() method of the string to split the file name into a list of parts. We pass the dot (".") character as the separator to split the file name into its name and extension components.
Next, we extract the last element of the list as the extension using the index -1, which refers to the last element of the list.
Finally, we print the extension to confirm that it was extracted correctly. Note that if the file name does not contain a dot character, this program will raise an IndexError exception when trying to extract the extension. To avoid this, you can check whether the list returned by split() contains more than one element before extracting the extension.