Curious issue with simple code

Tim Chase python.list at
Tue Sep 19 19:50:47 CEST 2006

 > [code]
 > import os
 > def print_tree(start_dir):
 >     for f in os.listdir(start_dir):
 >         fp = os.path.join(start_dir, f)
 >         print fp
 >         if os.path.isfile(fp): # will return false if use f here!
 >             if os.path.splitext(fp)[1] == '.html':
 >                 print 'html file found!'
 >         if os.path.isdir(fp):
 >             print_tree(fp)
 > print os.path
 > print_tree(r'c:\intent\docn')
 > [/code]
 > As above it all works as expected. However, on the marked
 > line, if I use f instead of fp then that condition returns
 > false! Surely, isfile(f) should return true, even if I
 > just give a filename, rather than the full path?
 > If anyway can explain this I'd be grateful,

If your current working directory (CWD) is the same as
start_dir, the behaviors of using "f" and "fp" will be the
same.  However, if your CWD is *not* the same, "f" is
relative to the CWD, and fp is "start_dir + f" relative to
the CWD.


 >>> start_dir = 'temp'
 >>> os.path.abspath(os.path.curdir)
 >>> f = 'filename'
 >>> fp = os.path.join(start_dir, f)
 >>> fp
 >>> os.path.abspath(f)
 >>> os.path.abspath(fp)

You may also want to read up on os.walk:

for root, dirs, files in os.walk(start_dir):
     for f in files:
         if os.path.splitext(f)[1].lower()[1:] == 'html':
             print 'HTML:', os.path.join(root, f)
             #print 'Not HTML:', os.path.join(root, f)

which allows you to easily do what it looks like your code
is doing.


More information about the Python-list mailing list