2009/3/12 Christian Heimes <li...@cheimes.de>: > Vlastimil Brom wrote: >> def path_from_pardir(path): >> return >> os.path.realpath(os.path.normpath(os.path.join(os.path.dirname(__file__), >> os.pardir, path))) >> # __file__ is substituted with sys.path[0] if not present >> >> real_path = path_from_pardir("txt/text_1.txt") >> >> The above seems to work both on windows and linux, but it very much >> looks like woodoo code for me; > > The canonical way to get the directory of a Python file is > > os.path.dirname(os.path.abspath(__file__)) > > __file__ is the relative or absolute path to the .py(c) file. > os,path.abspath() makes sure it's an absolute path. os.path.dirname() > returns the name of the directory. I usually store the directory as a > global name 'HERE'. > > >From here on you can traverse the file system. > os.path.abspath(os.path.join(HERE, os.pardir, somename)) gives you > "../somename" relative to the directory where your .py(c) is stored. > > Christian > Thanks for the clarification Christian, it's much clearer this way! Is it true, that I don't have to bother with realpath(), if I only use real directories i my program? (lacking the proper experiences with linux, I don't know, whether the symlinks could be yet otherwhere (upwards) in the path) Also, is it the right approach to substitute __file__ with sys.path[0] if it is not available? (like the executable generated using py2exe).
thanks again, Vlasta -- http://mail.python.org/mailman/listinfo/python-list