[Tutor] Python open of c:\ path Problem

Lie Ryan lie.1296 at gmail.com
Mon Aug 25 12:10:09 CEST 2008


> Message: 7
> Date: Sun, 24 Aug 2008 00:21:45 +0100
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Subject: Re: [Tutor] Python open of c:\ path Problem
> To: tutor at python.org
> Message-ID: <g8q62a$msi$1 at ger.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>         reply-type=original
> 
> 
> "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(
> "a:/very/long/path/name/that/needs/a/whole/line/to./itself.py",
> "w")
> 
> becomes
> 
> f = open("a:/very/long/path/name/" +
>               "that/needs/a/whole/" +
>               "line/to./itself.py","w")
> 
> 
> or by using a line continuation character.
> 
> f = open("a:/very/long/path/name/" \
>               "that/needs/a/whole/" \
>               "line/to./itself.py", "w")
> 

You don't even need the line continuation character, you can use
implicit line continuation character (since it's inside a parentheses)

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

> HTH,
> 



More information about the Tutor mailing list