drowningincode
drowningincode

Reputation: 1225

os.walk not giving right path

I am using the following code to open files from a directory.

for root, dirs, files in os.walk("./Boards"):
#Eliminate hidden files
files=[f for f in files if not f.startswith('.')]
for f, file in enumerate(files):
    print "ROOT: " + str(root)
    fileName=os.path.join(root,file)
    print fileName

When I run this i get this error

ROOT: ./Boards/AbuseSupport
./Boards/AbuseSupport/thread_title_11151.xml
ROOT: <Element 'board' at 0x1048ae450>

Can anyone explain how this happens and how I can fix it

Upvotes: 1

Views: 870

Answers (2)

nzaccardi
nzaccardi

Reputation: 394

I created a base directory structure of:

/Boards
/Boards/a.txt
/Boards/b.txt
/.ssh

I used the following code:

import os

for root, dirs, files in os.walk("./Boards"):
    #Eliminate hidden files
    files=[f for f in files if not f.startswith('.')]
    for f, file in enumerate(files):
        print "ROOT: " + str(root)
        fileName=os.path.join(root,file)
        print fileName

And I got the following response:

>> ROOT: ./Boards
>> ./Boards/a.txt
>> ROOT: ./Boards
>> ./Boards/b.txt
>> ROOT: ./Boards
>> ./Boards/c.txt

Mac OS 10.8.3 - Homebrew Python 2.7.3

I think you issue is that somehow you have assigned root to an XML Element object. Is there other code using an XML library?

Upvotes: 0

Ye Liu
Ye Liu

Reputation: 8976

I think the problem is that you're reusing the root variable while you're walking the directory and parsing XML at the same time. After you've parsed one XML file, the root variable became the root element of parse tree, but in next iteration of the loop, you are still using root variable as the directory name.

Upvotes: 1

Related Questions