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
答案 0 :(得分: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)))
答案 1 :(得分:0)
来自os.walk
文档:
通过遍历树来生成目录树中的文件名 自上而下或自下而上。对于以树为根的树中的每个目录 目录顶部(包括顶部本身),它产生一个3元组
(dirpath, dirnames, filenames)
。
dirpath
是一个字符串,即目录的路径。dirnames
是一个列表dirpath
中子目录的名称(不包括'。'和'..')。filenames
是非目录文件名称的列表dirpath
。
使用os.walk
的正确方法是:
for root, dirs, files in os.walk('/some/path'):
for file in files:
... # do something
请注意,os.walk
将递归遍历目录中的所有子目录。如果这不是您想要的,请使用os.listdir
。
答案 2 :(得分:0)
你使用了错误的功能。 os.walk
用于沿文件系统的层次结构向下移动,并返回(dirpath, dirnames, filenames)
的元组。
要返回目录中的文件列表,请使用os.listdir(path)
。
答案 3 :(得分:0)
os.walk()的返回值是一个元组。
(dirpath,dirnames,filenames)
尝试:
import React from 'react'
import ReactDOM from 'react-dom'
import expect from 'expect'
import TestUtils from 'react-addons-test-utils'
import Clock, { formatSeconds } from '../components/Clock' // import formatSeconds as well
describe('Clock', () => {
it('should exist', () => {
expect(Clock).toExist()
})
describe('formatSeconds', () => {
it('should format seconds', () => {
const seconds = 615
const expected = '10:15'
const actual = formatSeconds(seconds) // use it by itself
expect(actual).toBe(expected)
})
})
})