Exercise 23

Write a Python program that prompts the user to enter a file name, and then returns the extension of the file. Example if the user enters coursPython.pdf the program returns the message "The file extension is .pdf".

Solution

filename = input("Enter a filename: ")
extension = filename.split(".")[-1]
print("The file extension is ." + extension)
"""
Example usage:

Enter a filename: coursPython.pdf
The file extension is .pdf
"""

Note

Explanation:

  1. We use the input() function: in order to prompts the user to enter a filename.
  2. Then, the split() function: is used to separate the filename into a list of strings using the period (.) as the separator.
  3. The [-1] index: is used to retrieve the last item in the list, which is the file extension.
  4. Finally: the file extension is printed to the screen using the print() function.

This program assumes that the user will enter a valid file name with an extension. If the user enters a file name without an extension or with multiple periods, the program may not work as intended.



 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 23: Python algorithm that extract the file extension”

Leave a Reply