How to Concatenate Strings into File Paths in Python
Description
When concatenating path strings manually, it’s easy to make mistakes such as omitting a slash or backslash. Using os.path.join lets the function concatenate the strings as a path automatically.
Code
>>> import os
>>> base_path = "C:/Users/A/B"
>>> base_path+"C"+"D"
'C:/Users/A/BCD'
>>> os.path.join(base_path, "C", "D")
'C:/Users/A/B\\C\\D'
Environment
- Windows 11
- Python 3.10.11
