open filename with spaces in path

Kam-Hung Soh kamhung.soh at gmail.com
Tue May 6 19:09:08 EDT 2008


On Wed, 07 May 2008 08:36:35 +1000, Michael Robertson  
<mcrobertson at hotmail.com> wrote:

> I'm having trouble opening a file in linux, whose path has spaces in it.
>
> $ mkdir my\ test
> $ echo test > my\ test/test.txt
> $ python
>
>  >>> open('./my test/test.txt')
> Exception
>  >>> open('./my\\ test/test.txt')
> Exception
>

Try a string literal by prefixing your path string with "r":

open(r'./my test/test.txt')

See http://docs.python.org/ref/strings.html

> but yet...
>
>  >>> import os
>  >>> os.chdir('./my test')
>  >>> open('./test')
>
> works just fine.

Couldn't test on Linux, but in Windows ...

>>> os.chdir('C:\temp\my test')
Traceback (most recent call last):
   File "<interactive input>", line 1, in <module>
WindowsError: [Error 123] The filename, directory name, or volume label  
syntax is incorrect: 'C:\temp\\my test'

-- 
Kam-Hung Soh <a href="http://kamhungsoh.com/blog">Software Salariman</a>



More information about the Python-list mailing list