A silly question on file opening

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Feb 10 22:23:08 CET 2010

On Wed, 10 Feb 2010 12:42:17 -0800, joy99 wrote:

> I tried to change the location to D:\file and as I saw in Python Docs
> the file reading option is now "r+" so I changed the statement to
>    file_open=open("D:\file","r+")
> but it is still giving error.

You should copy and paste (do not re-type!) the *exact* line that leads 
to an error, and the full traceback that Python prints.

But in this case I can guess what the problem is. Like most C-inspired 
languages, Python uses backslashes to put in special characters: e.g. \n 
for newline, \t for tab, and \f for formfeed.

So when you try to open "D:\file" you are actually looking for a file on 
D drive called (chr(12) + "ile"), not "file".

The solution to this is to remember that Windows accepts forward slashes 
as well as backslashes, and always use the forward slash. So try:


and see if that works.

>>> print "D:\file"
>>> print "D:/file"


More information about the Python-list mailing list