0

just want to ask if this code in python is valid to use on any OS, i mean, i want to use the path then for exporting txt file to desktop so for example if user on Mac will not have problem, or is there another way to do it?

def get_path():
    PATH = os.path.normpath(os.path.expanduser('~/Desktop'))
    return PATH
  • check this https://stackoverflow.com/questions/34275782/how-to-get-desktop-location – Rafael Oct 18 '22 at 16:01
  • Does this answer your question? [How to get Desktop location?](https://stackoverflow.com/questions/34275782/how-to-get-desktop-location) – Buzz Oct 18 '22 at 16:14

2 Answers2

0

On windows you can easily get Desktop path by joining with the environment variable of user. Here is an example:

import os

desktop_path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
rafathasan
  • 524
  • 3
  • 15
  • expanduser, which is what OP uses, seems to be fine to expand ~ to the home directory. See https://stackoverflow.com/a/2057072/1319284 – kutschkem Oct 18 '22 at 16:09
  • Your referring to a linux based problem but this is on windows. – rafathasan Oct 18 '22 at 16:16
  • The point is exapanduser works on both Linux and WIndows: https://docs.python.org/3/library/os.path.html#os.path.expanduser – kutschkem Oct 19 '22 at 10:12
0

This should work for most users, Windows as well as Linux and MacOS have their desktop (typically) located under ~/Desktop. Do note however this location can be changed by the user so there is no guarantuee.

Windows: Usually ~/Desktop but can be changed, see https://superuser.com/q/1663587/138216

Linux: Typically ~/Desktop but could be something else, see https://unix.stackexchange.com/questions/391915/where-is-the-path-to-the-current-users-desktop-directory-stored

Mac: Also typcially ~/Desktop http://etutorials.org/Mac+OS/mac+os+x+power+tools/Part+II+Files+Finders+Docks+and+Apps+Including+Classic/Chapter+5+Finagle+Files+and+Foil+Finder+Frustration/The+Desktop+and+the+Desktop+Folder/#:~:text=In%20Mac%20OS%20X%2C%20because,these%20folders%20in%20Chapter%201).

kutschkem
  • 7,826
  • 3
  • 21
  • 56