I am creating a program and in this program, my folder structure is something like this
-> images
-> image_1.png
-> test.py
In test.py
, I need to access image_1.png
via a relative path such as images/image_1.png
in Linux. But in windows, it's images\image_1.png
.
From my research, I have found out that /
also works in windows as a path separator. Is this applicable to this case? Do I need to use os.sep
or something like that, or in all relative paths /
will work fine as a path separator in both windows and Linux?
CodePudding user response:
You can use os.path.normpath
as shown below. It can adjust to both Linux and Windows as per the system and it also resolves the path into the shortest possible path to the destination. Ex: /home/foo/../A
will be resolved to /home/A
.
Usage:
import os.path
# Path
path = './home//user/Documents'
# Normalize the specified path
# using os.path.normpath() method
norm_path = os.path.normpath(path)
# Print the normalized path
print(norm_path)
# prints home/user/Documents in Linux
# prints home\user\Documents in Windows
For more info read this article: https://www.geeksforgeeks.org/python-os-path-normpath-method/