0
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

3 Answers3

1

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)))
Daniel Jonsson
  • 2,483
  • 3
  • 36
  • 58
0

You're using the wrong function. os.walk is for walking down the hierarchy of a filesystem, and returns a tuple of (dirpath, dirnames, filenames).

To return the list of files in a directory, use os.listdir(path).

Daniel Roseman
  • 541,889
  • 55
  • 754
  • 786
0

Return value of os.walk() is a tuple.

(dirpath, dirnames, filenames)

try:

for root, dir, files in os.walk("Path of a directory"):
    for file in files:
        print(os.path.getmtime(os.path.abspath(file)))
BoilingFire
  • 181
  • 1
  • 9