Cross-platform Desktop directory path?

后端 未结 2 1733
暖寄归人
暖寄归人 2020-12-16 15:03

Is there a way of obtaining the Desktop directory path in a cross-platform way, ideally only using standard modules, in Python?

My current

相关标签:
2条回答
  • 2020-12-16 15:19

    Underneath windows, the users home is %HOMEPATH% which is the equivalent of the linux and Mac ~. Underneath this, there is a folder Desktop just like on Mac. Python automatically converts ~ to %HOMEPATH% on windows, so your Mac command will work out of the box on Mac and Windows.

    On Linux, it's a bit trickier. First, understand that the Linux box you are running on may not have a desktop, so no user desktop folder. If you do have window manager, it may or may not follow the ~\Desktop paradigm. The wikipedia entry on window managers goes into far more detail, including comparisons between several of the more popular X window managers in some of the sublinks.

    Your best bet would be to step back, and ask yourself why do I want/need the users desktop folder? Is it to create a shortcut during the install? You are likely better off with a installation writer utility, such as nsis, handling those details. If it's for file storage, even temporary, you may want to rethink your design. Or are you looking for something, in which case a file system search may be the way to go, instead of a brittle single folder check.

    Like most things, it all depends on what you want to accomplish.

    As EOL noted in his comment, Windows is slightly trickier than it first appears. His link to a more complete article on the Windows Desktop folder has more details on localization for the desktop folder. This is very important for builders of international applications to take into account, either using automatic localization built into their toolset, or avoiding things that use it.

    0 讨论(0)
  • 2020-12-16 15:29

    I used the following:

    import os
    desktop_file = os.path.expanduser("~/Desktop/myfile.txt")
    

    On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user‘s home directory.

    Reference: os.path.expanduser

    0 讨论(0)
提交回复
热议问题