How to detect the presence of a html file

Kent Johnson kent at kentsjohnson.com
Fri Dec 9 14:12:11 EST 2005


Phoe6 wrote:
> Operating System: Windows
> Python version: 2.4
> 
> I have bookmarks.html and wumpus.c under my c:
> 
> When I tried to check the presence of the bookmarks.html, I fail.
> 
> 
>>>>os.path.isfile('c:\bookmarks.html')
> 
> False
> 
>>>>os.path.isfile('c:\wumpus.c')
> 
> True

The problem is that \ is special in string literals. \b is a backspace 
character, not the two-character sequence you expect. \w has no special 
meaning so it *is* the two-character sequence you expect.

  >>> len('\b')
1
  >>> len('\w')
2

The simplest fix is to use raw strings for all your Windows path needs:
os.path.isfile(r'c:\bookmarks.html')
os.path.isfile(r'c:\wumpus.c')

In raw strings the only \ escapes are \' and \", everything else is left 
alone.
  >>> len(r'\b')
2
  >>> len(r'\w')
2

Kent



More information about the Python-list mailing list