In Python, we can easily extract the extension of a file from its name using various methods.
The extension of a file is the part of the file name that comes after the last dot character.
For example, in the file name “example.txt”, the extension is “txt”.
To extract the extension of a file using Python, we can use the os
module, which provides various functions for working with files and directories.
Here’s a Python program that extracts the extension from a given file name:
import os filename = "example.txt" extension = os.path.splitext(filename)[1] print(extension)
In this program, we first import the os
module. We then define a variable filename
that contains the name of the file whose extension we want to extract.
Next, we use the os.path.splitext()
function to split the file name into its base name and extension.
This function returns a tuple containing the base name and extension of the file, separated by a dot.
We then access the second element of this tuple, which contains the extension, and assign it to a variable extension
.
Finally, we print the extension
variable to the console, which will output the extension of the file “example.txt” as “.txt”.
We can also modify this program to extract the extension from a user-provided file name.
Here’s the modified program:
import os filename = input("Enter the file name: ") extension = os.path.splitext(filename)[1] print(extension)
In this program, we use the input()
function to prompt the user to enter the name of the file whose extension they want to extract.
We then pass this filename to the os.path.splitext()
function to extract the extension, which is then printed to the console.
In conclusion, extracting the extension from a file name using Python is a simple task that can be accomplished using the os.path.splitext()
function.
This function splits a file name into its base name and extension and returns them as a tuple, which can then be accessed to extract the extension.