Multiplatform scripts: Can I avoid os.sep?

G

gmax2006

Hi,

I am developing scripts that must run on both Linux and windows.

My scripts contain lots of relative paths (such as log\\log.txt or
ctl\\table.ctl) If I use os.sep, it makes the code ugly. Is there any
tips or techniques to have Python automatically converts \\ to / when
the script runs on Linux? What is the best way to deal with this
situation?

Thank you,
Max
 
M

Mike Kent

gmax2006 said:
Hi,

I am developing scripts that must run on both Linux and windows.

My scripts contain lots of relative paths (such as log\\log.txt or
ctl\\table.ctl) If I use os.sep, it makes the code ugly. Is there any
tips or techniques to have Python automatically converts \\ to / when
the script runs on Linux? What is the best way to deal with this
situation?

Use Jason Orendorff's path module:

http://www.jorendorff.com/articles/python/path/

Then you can do things like:

targetPath = 'some' / 'random' / 'path'

and the overridden '/' operator will do the right thing for the OS you
are on.
Of course, using the '/' operator in this manner makes some people's
heads explode.
 
B

Bruno Desthuilliers

gmax2006 said:
Hi,

I am developing scripts that must run on both Linux and windows.

My scripts contain lots of relative paths (such as log\\log.txt or
ctl\\table.ctl) If I use os.sep, it makes the code ugly. Is there any
tips or techniques to have Python automatically converts \\ to / when
the script runs on Linux? What is the best way to deal with this
situation?

os.path.join('log', 'log.txt')
os.path.join('ctl', 'table.ctl')

Or look for the 'path' module
http://www.jorendorff.com/articles/python/path/

HTH
 
F

Fredrik Lundh

gmax2006 said:
I am developing scripts that must run on both Linux and windows.

My scripts contain lots of relative paths (such as log\\log.txt or
ctl\\table.ctl) If I use os.sep, it makes the code ugly. Is there any
tips or techniques to have Python automatically converts \\ to / when
the script runs on Linux? What is the best way to deal with this
situation?

forward slashes work just fine on Windows too, in almost all cases.

(for the few cases when they don't work, use os.path.normpath and
friends to fix them up).

</F>
 
B

Bruno Desthuilliers

Mike Kent wrote:
(snip - about Jason Orendorff's path module)
Of course, using the '/' operator in this manner makes some people's
heads explode.

+1 QOTW
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top