python os.path.exists failure

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Sun Nov 1 11:38:39 CET 2009


koranthala schreef:
> Hi all,
>    My code is as follows:
> 
> path = r'C:/"Program Files"/testfolder/2.3/test.txt'
> if os.path.lexists(path):
>     print 'Path Exists'
> else:
>     print 'No file found in path - %s' %path
> print Popen(path, stdout=PIPE, shell=True).stdout.read()
> 
> The output comes as
> No file found in path - C:/"Program Files"/testfolder/2.3/test.txt
> but the test.txt file is opened.
> 
> The issue, I guess, is that the double quotes inside is failing the
> check. But without the double quotes, Popen fails.
> One solution, I can think is to check without double quotes, and then
> using some code, put the double quotes back inside, but it looks quite
> kludgy.

You can put the double quotes around the whole path instead of just
around "Program Files" in the call to Popen().

The issue here is actually that os.path.exists() (and all other Python
functions) use the path exactly like you pass it; but with your call to
Popen(), the path is passed as an argument to the shell, and it needs to
be quoted for the shell to interpret that correctly.

So here's what I would do: first specify the path literally without
quotes, and quote it only when needed:

path = r'C:/Program Files/testfolder/2.3/test.txt'
if os.path.lexists(path):
    print 'Path Exists'
else:
    print 'No file found in path - %s' %path
print Popen('"%s"' % path, stdout=PIPE, shell=True).stdout.read()

Some other notes:
- Since you use forward slashes, there's no need to use a raw string
literal.
- You can just as well use os.path.exists() instead of
os.path.lexists(). The difference has to do with symbolic links, which
Windows doesn't have.
- I'm not sure what you expect the line with Popen to do. On my system,
it opens the specified text file in notepad and returns an empty string.
If that's what you want to do, it's easier with os.startfile().

-- 
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
  -- Isaac Asimov

Roel Schroeven



More information about the Python-list mailing list