Mr Mystery Guest
Mr Mystery Guest

Reputation: 1474

File exists - no such file

import os

myDir = "C:\\temp\\a"


for root, dirs, files in os.walk(myDir):
  for file in files:
    # fname = os.path.join(root, file) # this works fine, yeah!
    fname = os.path.join(myDir, file)
    print ("%r" % (fname))
    src = os.path.isfile(fname)
    if src == False:
      print ("%r :Fail" % (fname))
    f = open(fname,"r")
    f.close()

I expected the two versions of fname to be the same, but I've found out the hard way that the above code doesn't work. I just want to know why, that's all.

Upvotes: 0

Views: 51

Answers (1)

tobias_k
tobias_k

Reputation: 82899

The problem is that os.walk(myDir) walks all the subdirectories, recursively! When walk descends into a subdirectory, root will be that directory, while myDir is still the root directory the search started in.

Let's say you have a file C:\temp\a\b\c\foo.txt. When os.walk descends into c, myDir is still C:\temp\a and root is C:\temp\a\b\c. Then os.path.join(root, file) will yield C:\temp\a\b\c\foo.txt, while os.path.join(myDir, file) gives C:\temp\a\foo.txt.

You might want to rename your myDir variable to root, and root to current, respectively, so it's less confusing.

Upvotes: 2

Related Questions