cross platform accessing paths (windows, linux ...)

V

Vlastimil Brom

Hi all,
I'd like to ask for some advice on how to acomplish file access in a
cross platform way.
My application is a kind of viewer of text and corresponding image
files (stored in separate subdirectories) and I'm going to deploy it
as binaries for windows and source files (again in separate
directories);
Of course the text and image data should be shared for the source and
executable version.
The program should be runnable without instalation, e.g. directly from
a CD-ROM, flashdisk etc. (supposing the working python ...
installation while using the source version).
the directory structure looks like:
my_viewer
- src
- bin
- txt
- img

While writing the source on windows, I didn't notice problems, as the
simple path
"../txt/text_1.txt"
worked well with open(...). (script file executed with the associated
python.exe)
However on Linux (Kubuntu 8.0.4) the files in neighbour directories
were not found most of the time (probably depending on how the script
was run - console; file manager Krusader ...)
After a lot of trials and gradually solving some corner issues, I
ended up with:

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;
as I have rather limited experiences on Linux, I'd like to ask, how
this would be best done in a cross platform way; or is the above realy
the way to go?
(I hope, using / as path separator should be fine, as it is also
supported on windows and other OS would use the slash anyway; is it
true, or do I have to use os.sep (which would complicate the code
slightly more)?
Are there any issues I'm likely to run into say on Mac with this approach?

I'm using python 2.5.4 on windows XPp SP3, and the default python
2.5.2 on Kubuntu 8.0.4;
(as I probably can't reasonably use 2.6 here for deployment with py2exe).

Any hints or comments are much appreciated; thanks in advance!

regards,
Vlasta
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top