w3resource

Python: Divide a path on the extension separator


Path Extension Splitter

Write a Python program to divide a path by the extension separator.

Sample Solution:

Python Code:

# Import the 'os.path' module for working with file paths.
import os.path
# Iterate through a list of example file paths.
for path in ['test.txt', 'filename', '/user/system/test.txt', '/', '']:
    # Print the file path and its corresponding file extension using 'os.path.splitext()'.
    print('"%s" :' % path, os.path.splitext(path))

Sample Output:

"test.txt" : ('test', '.txt')                                      
"filename" : ('filename', '')                                      
"/user/system/test.txt" : ('/user/system/test', '.txt')            
"/" : ('/', '')                                                    
"" : ('', '') 

Flowchart:

Flowchart: Divide a path on the extension separator.

Python Code Editor:

 

Previous: Write a Python program to get the users environment.
Next: Write a Python program to retrieve file properties.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.