2017-06-27 7 views
0
for files in os.walk("Path of a directory"): 
    for file in files: 
     print(os.path.getmtime(os.path.abspath(file))) 

ディレクトリ内のすべてのファイルの変更時刻を印刷します。 なぜこのエラーが発生しますか? os.walkドキュメントからディレクトリをトラバースする際にエラーが発生しました。TypeError:Unicodeに強制する:文字列またはバッファが必要です。リストが見つかりません。

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

Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames) .

dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath .

os.walkを使用するための正しい方法は次のとおりです。

for root, dirs, files in os.walk('/some/path'): 
    for file in files: 
     ... # do something 

os.walkは再帰的にディレクトリ内のすべてのサブディレクトリを下にトラバースすること。これがあなたが望むものでない場合は、os.listdirを使用してください。

0

誤った機能を使用しています。 os.walkは、ファイルシステムの階層を下ろすためのもので、(dirpath, dirnames, filenames)のタプルを返します。

ディレクトリ内のファイルのリストを返すには、os.listdir(path)を使用します。

0

os.walk()の戻り値はタプルです。

(dirpath, dirnames, filenames)

試してみてください。

for root, dir, files in os.walk("Path of a directory"): 
    for file in files: 
     print(os.path.getmtime(os.path.abspath(file))) 
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))) 
関連する問題