How to get Desktop location?

后端 未结 7 646
情深已故
情深已故 2020-12-08 15:30

I\'m using Python on Windows and I want a part of my script to copy a file from a certain directory (I know its path) to the Desktop.

I used this:

sh         


        
相关标签:
7条回答
  • 2020-12-08 15:54

    You can use os.environ["HOMEPATH"] to get the path. Right now it's literally trying to find %HOMEPATH%/Desktop without substituting the actual path.

    Maybe something like:

    shutil.copy(txtName, os.path.join(os.environ["HOMEPATH"], "Desktop"))
    
    0 讨论(0)
  • 2020-12-08 15:56

    This works on both Windows and Linux:

    import os
    desktop = os.path.expanduser("~/Desktop")
    
    # the above is valid on Windows (after 7) but if you want it in os normalized form:
    desktop = os.path.normpath(os.path.expanduser("~/Desktop"))
    
    0 讨论(0)
  • 2020-12-08 16:04

    I can not comment yet, but solutions based on joining location to a user path with 'Desktop' have limited appliance because Desktop could and often is being remapped to a non-system drive. To get real location a windows registry should be used... or special functions via ctypes like https://stackoverflow.com/a/626927/7273599

    0 讨论(0)
  • 2020-12-08 16:05

    For 3.5+ you can use pathlib:

    import pathlib
    
    desktop = pathlib.Path.home() / 'Desktop'
    
    0 讨论(0)
  • 2020-12-08 16:08

    On Unix or Linux:

    import os
    desktop = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') 
    

    on Windows:

    import os
    desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop') 
    

    and to add in your command:

    shutil.copy(txtName, desktop)
    
    0 讨论(0)
  • 2020-12-08 16:11

    Try this:

    import os
    file1 =os.environ["HOMEPATH"] + "\Desktop\myfile.txt" 
    
    0 讨论(0)
提交回复
热议问题