odnochlen
Я читал, что __file__ не везде работает. И что лучше - dirname или abspath? Какой самый корректный вариант открытия файлов в каталоге програмы?
Не знаю самый ли корректный, но делаю так:
import os
import sys
def program_path():
main_file = unicode(sys.argv[0], sys.getfilesystemencoding())
return os.path.realpath(os.path.dirname(main_file))
На выходе Юникодовый путь до папки с программой, даже если это .exe сделанный cxFreeze и т.п.
odnochlen
Вопрос в догонку - а можно ли в конфигах сохранять пути с сепаратором, или надо мудрячить с os.path.join
Наверное, лучше сохранять с прямым слэшем, а потом на крайний случай использовать os.path.normpath(path)
os.path.normpath(path)
Normalize a pathname. This collapses redundant separators and up-level references so that A//B, A/B/, A/./B and A/foo/../B all become A/B.
It does not normalize the case (use normcase() for that). On Windows, it converts forward slashes to backward slashes. It should be understood that this may change the meaning of the path if it contains symbolic links!
Но Win нормально с ‘/’ работает.
odnochlen
А \ на линупсе будет работать?
нет
ubuntu@devbox:~$ python
Python 2.7.2+ (default, Oct 4 2011, 20:03:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open(r"tmp\test.txt")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'tmp\\test.txt'
>>> f = open(r"tmp/test.txt")
>>> f
<open file 'tmp/test.txt', mode 'r' at 0xb73dfe38>