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

我想打印目录中所有文件的修改时间。为什么会出现此错误?

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
4

3 回答 3

1

os.walk返回一个带值的元组。请参阅https://docs.python.org/2/library/os.html#os.walk上的文档。

这应该解决它:

for root, dirs, files in os.walk("Path of a directory"):
    for file in files:
        print(os.path.getmtime(os.path.abspath(file)))
于 2017-06-27T14:46:40.187 回答
0

您使用了错误的功能。os.walk用于遍历文件系统的层次结构,并返回(dirpath, dirnames, filenames).

要返回目录中的文件列表,请使用os.listdir(path).

于 2017-06-27T14:46:16.650 回答
0

os.walk() 的返回值是一个元组。

(目录路径、目录名、文件名)

尝试:

for root, dir, files in os.walk("Path of a directory"):
    for file in files:
        print(os.path.getmtime(os.path.abspath(file)))
于 2017-06-27T14:46:30.240 回答