[Tutor] slashes in paths

Dominik George nik at naturalnet.de
Sat Jul 20 22:06:59 CEST 2013


Hi,

> >>> soundfile13
> 'c:/python27/jimprogs/wav\\bicycle_bell.wav'
> >>>
> 
> with single forward slashes mixed with a double backslash
> 
> it comes out even worse if I print it
> 
> c:/python27/jimprogs/wav\bicycle_bell.wav  - no double backslash,
> which could create a mess if someone copied that and tried it.

That's because the interactive python interpreter has bad behaviour when
you just throw a name at it. It tries to find a good trade-off between
exact representation of the internal data and human readibility. The
result you see is printed in such a way that you can copy and paste it
as a Python string, with escaped backslashes.

When you use print, the human-readable string data is written to stdout,
with the literal backslashes that the string really contains.

> Oddly, the mixed path does work for playing sounds,
> 
> >>> import winsound
> >>> winsound.PlaySound('c:/python27/jimprogs/wav\\bicycle_bell.wav',winsound.SND_FILENAME)
> >>>
> That rings a bell.

This will work in any case. First of all, in this example code, the \\
creates a literal backslash in the string, so what is used in the end is
a single backslash. If that weren't the case, this would still work
because empty directory names are ignored in all reasonable operating
systems.

> But it just doesn't look right. If forward slash is a Python
> convention instead of double backslash, it should follow through. I
> can see where you could get in trouble with it.

Well, who says it is a Python convention? It is a POSIX convention, and
in your code above you jsut used that. Because Python is such a good
friend, it doesn't blow up but take what you gave to it. As you can see
by using the os.path.join() function is that on Windows, when you ask
Python to do the work for you, it really uses *single* backslashes.

-nik

-- 
<burny> Ein Jabber-Account, sie alle zu finden; ins Dunkel zu treiben
        und ewig zu binden; im NaturalNet, wo die Schatten droh'n ;)!

PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17  FD26 B79A 3C16 A0C4 F296
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 905 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/tutor/attachments/20130720/2da561a7/attachment.pgp>


More information about the Tutor mailing list