w3resource

Python: Join one or more path components together and split a given path in directory and file


13. Join and Split Path Components

Write a Python program to join one or more path components together and split a given path into directories and files.

Sample Solution:

Python Code :

import os
path = r'g:\\testpath\\a.txt'
print("Original path:")
print(path)
print("\nDir and file name of the said path:")
print(os.path.split(path))
print("\nJoin one or more path components together:")
print(os.path.join(r'g:\\testpath\\','a.txt'))

Sample Output:

Original path:
g:\\testpath\\a.txt

Dir and file name of the said path:
('', 'g:\\\\testpath\\\\a.txt')

Join one or more path components together:
g:\\testpath\\/a.txt

For more Practice: Solve these Related Problems:

  • Write a Python program to join multiple path components using os.path.join() and then split the resulting path into its constituent parts using os.path.split().
  • Write a Python script to construct a file path from a list of directories and a file name, then separate and print each component.
  • Write a Python function that takes individual path segments, joins them into a complete path, and then returns a list of directories from that path.
  • Write a Python program to create a normalized path from given components and then split it into directory and file portions using os.path.normpath() and os.path.split().

Previous: Write a Python program to test whether a given path exists or not. If the path exist find the filename and directory portion of the said path.
Next: Write a Python program to alter the owner and the group id of a specified file.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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.