os.path.isdir do not work for Foder named '2011-07-03'

Thomas Jollans t at jollybox.de
Tue Jul 19 02:30:34 EDT 2011


On 19/07/11 06:42, Steven D'Aprano wrote:
> Nulpum wrote:
> 
>> I want to make sure that folder exists.
>>
>> '2011-07-03' is really exists. but 'os.path.isdir' say false
>>
>> Does anyone know why?
> 
> Yes.
> 
>>>> print "logs/2011-07-03"
> logs/2011-07-03
>>>> print "logs\2011-07-03"
> logs�1-07-03
> 
> Don't use backslashes as path separators in Python. Backslashes are used for
> string escapes.
> 
> [snip]
>
> There are three solutions:
> 
> (1) Escape every backslash with an extra backslash:
> 
>>>> print "logs\\2011-07-03"
> logs\2011-07-03

There is a more elegant solution: use raw strings: r'c:\foo\bar'

> (2) Use forward slashes, as Windows will happily accept them instead of
> backslashes.

The "correct" solution in many cases is to not assume any particular
path separator at all, and use os.path.join when dealing with paths.
This will work even on systems that do not accept forward slashes as
path separators. (does Python still support any of those?)

> (3) Use another operating system. *wink*

This, of course, is the only truly tenable solution.

Thomas



More information about the Python-list mailing list