How to get FileSystem’s separator using Python

problem

You’re writing a program (e.g. AWS lambda) in Python that is using a file path and runs on various Operating Systems. For example, Windows OS uses a different separator in comparison with Mac OS.

Operating System File Path example
Windows
C:\Documents\Newsletters\Summer2018.pdf
Mac OS
/home/user/documents

SOLUTION

separator.py
				
					import os

print(os.path.sep)
				
			
output
default FS separator based on OS in Python

I just executed the program on a MacBook. The separator for Mac OS is /

conclusion

Since different operating systems have different path name conventions we need to take that into account when writing portable programs.

 

References:

https://docs.python.org/3/library/os.path.html 

https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats 

https://pressbooks.senecapolytechnic.ca/uli101/chapter/file-paths-in-linux/

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪