Doubled backslashes in Windows paths
Ned Batchelder
ned at nedbatchelder.com
Fri Oct 7 09:55:33 EDT 2016
On Friday, October 7, 2016 at 8:39:55 AM UTC-4, BartC wrote:
> On 07/10/2016 06:30, Oz-in-DFW wrote:
> > I'm using Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC
> > v.1900 32 bit (Intel)] on Windows 7
> >
> > I'm trying to write some file processing that looks at file size,
> > extensions, and several other things and I'm having trouble getting a
> > reliably usable path to files.
> >
> > The problem *seems* to be doubled backslashes in the path, but I've read
> > elsewhere that this is just an artifact of the way the interpreter
> > displays the strings.
> >
> > I'm getting an error message on an os.path.getsize call;
> >
> > Path: -
> > "C:\Users\Rich\Desktop\2B_Proc\2307e60da6451986dd8d23635b845386.jpg" -
> > Traceback (most recent call last):
> > File "C:\Users\Rich\workspace\PyTest\test.py", line 19, in <module>
> > if os.path.getsize(path)>10000:
> > File "C:\Python32\lib\genericpath.py", line 49, in getsize
> > return os.stat(filename).st_size
> > WindowsError: [Error 123] The filename, directory name, or volume
> > label syntax is incorrect:
> > '"C:\\Users\\Rich\\Desktop\\2B_Proc\\2307e60da6451986dd8d23635b845386.jpg"'
>
> I tried to recreate this error and it seems the getsize function doesn't
> like quotes in the path.
>
> Whether \ is correctly written as \\ in a string literal, or a raw
> string is used with the r prefix and a single \, or a \ has been put
> into path by any other means, then these will still be displayed as \\
> in the error message, which is strange. The error handler is expanding \
> characters to \\.
For error messages destined for developers, it is good practice to use
%r or {!r} to get the repr() of a string. This will show quotes around
the string, and use backslash escapes to present the contents
unambiguously. That's what's expanding \ to \\, and adding the single
quotes you see in the message.
--Ned.
More information about the Python-list
mailing list