thekindlyone
thekindlyone

Reputation: 509

How do I convert a double slashed path to a path that open() accepts?

I have a raw string representing a path on windows like this: 'F:\\Music\\v flac\\1-06 No Quarter.flac\r' What should I do to it so that open() accepts it? os.path.normpath() isn't working.

>>> path
'F:\\Music\\v flac\\1-06 No Quarter.flac\r'
>>> fp=open(path,'rb')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 22] invalid mode ('rb') or filename: 'F:\\Music\\v flac\\1-06 No
 Quarter.flac\r'
>>> fp=open(os.path.normpath(path),'rb')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 22] invalid mode ('rb') or filename: 'F:\\Music\\v flac\\1-06 No
 Quarter.flac\r'
>>>

Upvotes: 1

Views: 230

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124070

The double slashes are not the problem here. It is the \r carriage return character at the end that is causing you problems.

String it from the path:

fp = open(path.strip(), 'rb')

Python is merely showing a string literal representation of your path string, for ease of debugging. Any character with special meaning, outside of the printable ASCII range, is escaped, including backslashes. The value itself does not have doubled backslashes:

>>> path = 'F:\\Music\\v flac\\1-06 No Quarter.flac\r'
>>> path
'F:\\Music\\v flac\\1-06 No Quarter.flac\r'
>>> print path
F:\Music\v flac\1-06 No Quarter.flac
>>> path[:3]
'F:\\'
>>> len(path[:3])
3

Note how printing path shows the path value having only single backslashes and how the first 3 characters of the path are F:\, the string having length 3 and not 4. In a Python string literal the backslashes would denote escape sequences however, so Python escapes those too.

Upvotes: 5

Related Questions