1# Python program to explain os.path.join() method
2
3# importing os module
4import os
5
6# Path
7path = "/home"
8
9# Join various path components
10print(os.path.join(path, "User/Desktop", "file.txt"))
11
12
13# Path
14path = "User/Documents"
15
16# Join various path components
17print(os.path.join(path, "/home", "file.txt"))
18
19# In above example '/home'
20# represents an absolute path
21# so all previous components i.e User / Documents
22# are thrown away and joining continues
23# from the absolute path component i.e / home.
24
25
26# Path
27path = "/User"
28
29# Join various path components
30print(os.path.join(path, "Downloads", "file.txt", "/home"))
31
32# In above example '/User' and '/home'
33# both represents an absolute path
34# but '/home' is the last value
35# so all previous components before '/home'
36# will be discarded and joining will
37# continue from '/home'
38
39# Path
40path = "/home"
41
42# Join various path components
43print(os.path.join(path, "User/Public/", "Documents", ""))
44
45# In above example the last
46# path component is empty
47# so a directory seperator ('/')
48# will be put at the end
49# along with the concatenated value
50
1import os
2
3# Join paths using OS import. Takes any amount of arguments
4path = os.path.join('/var/www/public_html', './app/', ".\\my_file.json")
5
6print(path) # /var/www/public_html/app/myfile.json