简体   繁体   中英

Error while listing files in directory recursively using python

I am trying to list all the file ending with '.py'. The way I want it to be displayed is dirname + filename . I am using os.path.join() for this. I am getting an error when I put /Users as the starting point. But when I specify the directory where most of the '.py' files are like os.walk(r'/Users/name/Pythonfiles') I don't get the error.

This is the code I came up with:

for cdir, dir, files in os.walk(r'/Users'):
    for file in files:
        if file.endswith('.py'):
            filename = os.path.join(cdir, file)
            print filename

Error that I am getting:

Traceback (most recent call last):
  File "/Users/name/PythonTutorials/finding_largest_file.py", line 9, in <module>
     filename = os.path.join(dir, file)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py", line 77, in join
     elif path == '' or path.endswith('/'):
AttributeError: 'list' object has no attribute 'ends with'

And please suggest a better way to accomplish this task if possible.

You are using the wrong value in your os.path.join() call. The current directory being iterated over is the first value given by os.walk() , which you assigned to cdir .

You are using the second value returned by os.walk() , which is a list of directory names.

Use:

for cdir, directories, files in os.walk(r'/Users'):
    for file in files:
        if file.endswith('.py'):
            filename = os.path.join(cdir, file)
            print filename

I renamed dir to directories ; a clearer name and also one that doesn't mask the built-in dir() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM