File Handling Problems Python I/O

Peter Hansen peter at engcorp.com
Thu Jan 6 16:58:00 CET 2005


Josh wrote:
> I am having a problem with Python. I am new to Python as a programming
> language, but I do have experience in other languages. I am
> experiencing strange problems with File handling and wonder if anyone
> else has seen this or knows what I am doing wrong. I am simply trying
> to open a file for read and iterate through until the end of file. I am
> able to do so without a problem, but here's the catch: The open
> statement is only working on certain files. I open a simple text file
> say file1.txt without any issues, but I change the open statement to
> another text file and it error's out stating the file doesn't exist. 

The usual rookie mistake here is to fail to recognize
that backslashes in strings are interpreted as special
escape sequences if they precede certain characters such
as "t" or "b".  You probably have a path that looks like
this: "c:\temp\myfile.txt", right?  The \t is actually
being converted into a TAB character.

You can use *forward* slashes in most cases in Windows,
except on the command line.  The simplest fix is just
to convert your backslashes to forward slashes:
   "c:/temp/myfile.txt"

Another approach, somewhat less desirable, is to use
"raw" strings instead, to prevent the escape sequences from
being recognized:
   r"c:\temp\myfile.txt"

Finally, and by far least desirable, use double-backslashes
to escape each backslash and in effect nullify the usual
escape handling:
   "c:\\temp\\myfile.txt"

Much less readable that way, but sometimes the right thing to do...

-Peter



More information about the Python-list mailing list