[Tutor] Python open of c:\ path Problem

Alan Gauld alan.gauld at btinternet.com
Sun Aug 24 01:21:45 CEST 2008

"Wayne Watson" <sierra_mtnview at sbcglobal.net> wrote

>    junkfile = open('c:\tmp\junkpythonfile','w')
> IOError: [Errno 2] No such file or directory: 
> 'c:\tmp\\junkpythonfile'
> I suspect the problem is with the back slash. Comments?

Correct. There are several ways round this, the simplest
being to use forward slashes which are effectively portable
across most OSs.

   junkfile = open('c:/tmp/junkpythonfile','w')

You could use a raw string by prefixing the string with r

    junkfile = open(r'c:\tmp\junkpythonfile','w')

Or you could escape the backslash

   junkfile = open('c:\\tmp\\junkpythonfile','w')

> BTW, how does one continue a long statement
> that has, say, a long path to a file?

You can create a long string by adding the shorter string
elements :

f = open(


f = open("a:/very/long/path/name/" +
              "that/needs/a/whole/" +

or by using a line continuation character.

f = open("a:/very/long/path/name/" \
              "that/needs/a/whole/" \
              "line/to./itself.py", "w")


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list