On Friday, July 10, 2015 at 11:18:57 PM UTC+5:30, Rustom Mody wrote: > On Friday, July 10, 2015 at 8:56:48 PM UTC+5:30, Mark Storkamp wrote: > > MRAB wrote: > > > > > On 2015-07-10 15:27, Mark Storkamp via Python-list wrote: > > > > I'm just learning Python, and I've run into trouble trying to change > > > > directory to the windows My Documents directory. There's likely a better > > > > way to do this, but this is what I've tried so far: > > > > > > > > --------------------------------------------- > > > > from tkinter import Tk > > > > from tkinter.filedialog import askopenfilename > > > > > > > > import os > > > > > > > > Tk().withdraw() > > > > > > > > sourcedir = os.environ['HOME']+"/Documents/" > > > > os.chdir(sourcedir) > > > > src = askopenfilename() > > > > if src == '' : > > > > sys.exit() > > > > fin = open(src, mode='r') > > > > ## do stuff > > > > fin.close() > > > > ----------------------------------------------- > > > > > > > > When this is run from IDLE, it works fine. But when I double click on > > > > the saved file to run it, it quits without ever showing the open file > > > > dialog box, and doesn't show any error message. > > > > > > > > The problem is with the os.environ['HOME'] call. If I comment it out > > > > (and fix up the surrounding code with an absolute path) then it runs. > > > > But then it won't work properly for other users. > > > > > > > > Interestingly enough, when I moved this to a Mac so I could post to > > > > Usenet, I discovered it works fine on the Mac. Only Windows seems to be > > > > the problem. Windows 7. > > > > > > > > Any thoughts or suggestions? > > > > > > > Try os.path.expanduser(r'~\Documents'). > > > > > > It's a bad idea to use os.chdir; it's better to use absolute paths: > > > > > > src = askopenfilename(initialdir=os.path.expanduser(r'~\Documents')) > > > > I thought there must be a way to pass the directory to askopenfilename, > > but I just hadn't figured out how yet. > > > > The other suggestions for using HOMEPATH also worked for both Mac and > > Windows. > > > > Thanks. > > According to > http://serverfault.com/questions/29948/difference-between-profile-and-home-path > it seems %userprofile% is more current than %homepath% > [though windows arcana is not exactly my forte ;-) ]
which may need to be combined with something like: home = 'HOME' if os.name=='posix' else 'USERPROFILE' (see https://docs.python.org/2/library/os.html for os.name) -- https://mail.python.org/mailman/listinfo/python-list