1

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?

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Tested in Windows 11 and it works
Does this work on Mac too? (is it cross-operating system?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.