pythonlast-modifieddirectory-traversal

Error in traversing a directory TypeError: coercing to Unicode: need string or buffer, list found


for files in os.walk("Path of a directory"):
    for file in files:
        print(os.path.getmtime(os.path.abspath(file)))

I want to print modified time of all files in a directory. Why it gives this error?

Traceback (most recent call last):
  File "L:/script/python_scripts/dir_Traverse.py", line 7, in <module>
    print(os.path.getmtime(os.path.abspath(file)))
  File "C:\Python27\lib\ntpath.py", line 488, in abspath
    path = _getfullpathname(path)
TypeError: coercing to Unicode: need string or buffer, list found

Solution

  • os.walk returns a tuple with values. See the documentation on https://docs.python.org/2/library/os.html#os.walk.

    This should fix it:

    for root, dirs, files in os.walk("Path of a directory"):
        for file in files:
            print(os.path.getmtime(os.path.abspath(file)))