I was addicted to it unexpectedly, so I made a note.
Since the desktop path varies depending on the PC and user, describe how to obtain it for general purposes.
Python 2.7 Windows 7/8
#coding:cp932
import os
desktop_path = os.getenv("HOMEDRIVE") + os.getenv("HOMEPATH") + "\\Desktop"
print desktop_path
Execution result:
python
C:\Users\foo\Desktop
You can get environment variables with os.getenv ("???").
[Main environment variables (external link)](http://win.just4fun.biz/%E3%82%B3%E3%83%9E%E3%83%B3%E3%83%89%E3%83% 97% E3% 83% AD% E3% 83% B3% E3% 83% 97% E3% 83% 88 / Windows% E3% 81% AE% E4% B8% BB% E8% A6% 81% E3% 81% AA% E7% 92% B0% E5% A2% 83% E5% A4% 89% E6% 95% B0% E4% B8% 80% E8% A6% A7% E3% 81% A8% E6% 84% 8F% E5% 91% B3.html)
Since there is no environment variable that stores the desktop path itself, the above script creates the desktop path with a combination of environment variables.
I will also get my documents, pictures, etc.
#coding:cp932
import os
desktop_path = os.getenv("HOMEDRIVE") + os.getenv("HOMEPATH") + "\\Desktop"
mydocument_path = os.getenv("HOMEDRIVE") + os.getenv("HOMEPATH") + "\\Documents"
mypicrure_path = os.getenv("HOMEDRIVE") + os.getenv("HOMEPATH") + "\\Pictures"
myvideo_path = os.getenv("HOMEDRIVE") + os.getenv("HOMEPATH") + "\\Videos"
mymusic_path = os.getenv("HOMEDRIVE") + os.getenv("HOMEPATH") + "\\Music"
if os.path.exists(desktop_path):
print "desktop:" + desktop_path
if os.path.exists(mydocument_path):
print "document:" + mydocument_path
if os.path.exists(mypicrure_path):
print "Picture:" + mypicrure_path
if os.path.exists(myvideo_path):
print "video:" + myvideo_path
if os.path.exists(mymusic_path):
print "Music:" + mymusic_path
Execution result:
python
Desktop: C:\Users\foo\Desktop
Document: C:\Users\foo\Documents
Picture: C:\Users\foo\Pictures
Video: C:\Users\foo\Videos
Music: C:\Users\foo\Music
Recommended Posts