Extracting File Extension using Python

2023

In this project, we will discuss a Python code snippet that extracts the file extension from a file name. We'll explain each step of the code and provide the final working code at the end.


Getting User Input

To begin, we will prompt the user to enter a file name using the input() function. Let's store the user's input in a variable called filename:

filename = input("Enter your file name: ")

Extracting File Extension

Next, we will extract the file extension from the file name. We can achieve this by splitting the file name using the dot (".") as the separator and accessing the second element of the resulting list. Here's the code that performs this operation:

file_extension = filename.split(".")[1]

In this code, filename.split(".") splits the file name into a list of substrings using the dot as the separator. Then, we access the second element of the list using [1] to obtain the file extension.

Displaying the File Extension

Finally, we will display the extracted file extension to the user. We can use the print() function for this purpose:

print("Your file extension is:", file_extension)

This code will print the message "Your file extension is:" followed by the actual file extension.


Final Code

Here's the complete Python code that extracts the file extension from a file name:

filename = input("Enter your file name: ")
file_extension = filename.split(".")[1]
print("Your file extension is:", file_extension)

That's it! You now have a Python code snippet that extracts the file extension from a file name. Feel free to modify the code or use it as a starting point for your own projects. Happy coding!

Back