Doubled backslashes in Windows paths
Steve D'Aprano
steve+python at pearwood.info
Fri Oct 7 06:46:03 EDT 2016
On Fri, 7 Oct 2016 04:30 pm, 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.
Indeed.
Why don't you show us the actual path you use? You show us this snippet:
> path = '"'+dirpath+name+'"'
> path = os.path.normpath(path)
> print("Path: -",path,"-")
> if os.path.getsize(path)>10000:
> print("Path: ",path," Size:
> ",os.path.getsize(dirpath+name))
but apparently dirpath and name are secrets, because you don't show us what
they are *wink*
However, using my awesome powers of observation *grin* I see that your
filename (whatever it is) begins and ends with quotation marks. So instead
of having a file name like:
C:\Users\Rich\Desktop\2B_Proc\2307e60da6451986dd8d23635b845386.jpg
you actually have a file name like:
"C:\Users\Rich\Desktop\2B_Proc\2307e60da6451986dd8d23635b845386.jpg"
In this example, the quotation marks " at the beginning and end are *NOT*
the string delimiters, they are the first and last characters in the
string. Which might explain why Windows complains about the label:
> WindowsError: [Error 123] The filename, directory name, or volume
> label syntax is incorrect:
That's because
"C:
is an illegal volume label (disk name? I'm not really a Windows user, and
I'm not quite sure what the correct terminology here would be).
So I suggest you change your code from this:
> path = '"'+dirpath+name+'"'
> path = os.path.normpath(path)
to this instead:
path = dirpath + name
path = os.path.normpath(path)
> So the file is there and the path is correct. I'm adding quotes to the
> path to deal with directories and filenames that have spaces in them.
The os.path and os functions do not need you to escape the file name with
quotes to handle spaces.
It is very likely that if you call out to another Windows program using the
os.system() call you will need to worry about escaping the spaces, but
otherwise, you don't need them.
> If I drop the quotes, everything works as I expect
Indeed.
> *until* I encounter the first file/path with spaces.
And what happens then? My guess is that you get a different error, probably
in a different place.
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list