File Handling Problems Python I/O

Craig Ringer craig at postnewspapers.com.au
Fri Jan 7 00:54:18 EST 2005


On Fri, 2005-01-07 at 02:06, Josh wrote:
> Peter,
> 
> Thank you for the rookie correction. That was my exact problem. I
> changed the address to use forward slashes and it works perfect. I did
> not know that a backslash had special meaning within a string, but now
> I do! Thanks again

There's another common mistake you might want to head off now, too.
Consider the following program:

--------
directory = r"c:\mydata"
datafilename = "something.txt"

datafile = open(directory + datafilename,"r")
---------

It's very common for this to happen, usually when the paths are
originally written with trailing slashes then changed to not have them
later.

Rather than saying "all paths must have trailing slashes", manually
formatting in slashes, or other platform-specific uglyness, consider
using the os.path module to take care of it:

--------
import os

directory = r"c:\mydata"
datafilename = "something.txt"

datafile = open(os.path.join(directory,datafilename),"r")
--------

This will work on any platform (so long as the literal paths are
correct) and will work no matter whether or not there are trailing path
separators on the input strings. os.path.join can take more than two
arguments, too.

os.path has lots of other handy tools, so I strongly recommend checking
it out.

--
Craig Ringer




More information about the Python-list mailing list