Python File Paths in Real Code
A path names a file on disk. os.path tools read a path apart and build one up.
Build a path
join() joins one folder name and one file name. The slash fits this computer.
import os
path = os.path.join("photos", "cat.jpg")
print(path)Take the file name
basename() drops the folders. Only the file name is left.
import os
print(os.path.basename("photos/cat.jpg"))Split name and ending
splitext() gives back a pair. The name comes first, then the ending.
import os
print(os.path.splitext("report.pdf"))Example
import os
paths = ["docs/essay.txt", "photos/cat.jpg", "music/song.mp3"]
for path in paths:
name = os.path.basename(path)
root, ext = os.path.splitext(name)
print(root, ext)Key points
- Use os.path.join() to build a path from parts
- Use os.path.basename() to take the file name
- Use os.path.splitext() to split name and ending
- Use splitext()[1] for the ending alone
- join() picks the right slash for the computer
In this example, the list holds three paths. basename() takes the file name from each path. splitext() then splits each name into a root and an ending. Each printout shows the root first and the ending second.
Note
A path built by hand with + can break on another computer.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does os.path.splitext("a.txt") give back?