Home Ask Login Register

Developers Planet

Your answer is one click away!

goodgrief February 2016

Python local folder path for each platform

My script works in special folder, which name is "Fold". On the different computers and operation systems path to this folder is different. For example, on Mac it will: "/Users/user/Fold". On Windows - "C:\Users\user\Desktop\Fold" . How I can input the path to this folder in my Python script for working on each platform? What should I type inside my script, if the script works only inside "Fold" folder?


danidee February 2016

the os module has the functionality for identifying various operating systems

in your code you can do this

import os

if os.name == 'nt'
    # do something nt stands for windows
    path = 'C:\Users\user\Desktop\Fold'
elif os.name == 'posix'
    # linux or mac
    path = '/home/user/Desktop/Fold'

the platform module gives more details than the os module the os might return posix for both linux and mac on my linux machine platform outputs this

import platform

>>> print(platform.system())
>>> print(platform.release())

platform.system() should return 'Darwin' for mac

Jeremad February 2016

You can use

import sys
import os
sys.platform == "win32":
    fold = os.path.join("C:", "Users", "user", "Desktop", "Fold")
elif sys.platform == "Darwin":
    fold = os.path.join("/Users", "user", "Fold")

Or you can setup an environment variable on each computer if it changes within a same OS.

nd. February 2016

You can get the path to the user folder (Mac: /Users/user, Win: C:\Users\user\) via os.path.expanduser("~"). From there, your implementation seems OS-specific - maybe only the Windows-implementation places its data on the desktop. Since you can get the platform identifier via sys.platform, you could do something like this:

import sys, os
folderPath = os.path.join("Desktop", "Fold") if sys.platform == "win32" else "Fold"
fullPath = os.path.join(os.path.expanduser("~"), folderPath)

If you want to use the path to the desktop folder on other systems, please refer to Cross-platform Desktop directory path?

Post Status

Asked in February 2016
Viewed 2,273 times
Voted 14
Answered 3 times


Leave an answer

Quote of the day: live life