Common Usage of os.path
module
This article records some very common usages of os.path
module in Python.
Since there are few examples in the docs of os.path
module, I added examples for all part in this article.
os.path.expanduser()
Expand ~ and ~user constructions. If user or $HOME is unknown, do nothing.
1 | path = "~/file.txt" |
os.path.join()
Join one or more path components intelligently.
1 | 'a','b','c') os.path.join( |
os.path.split()
Split the pathname path into a pair, (head, tail)
where tail is the last pathname component and head is everything leading up to that.
- The tail part will never contain a slash;
- if path ends in a slash, tail will be empty.
- If there is no slash in path, head will be empty.
- If path is empty, both head and tail are empty.
1
2
3
4
5
6
7"/home/sa2y18/mydocuments" test_s=
os.path.split(test_s)
('/home/sa2y18', 'mydocuments')
'/' test_s=test_s+
os.path.split(test_s)
('/home/sa2y18/mydocuments', '')