我在不同文件夹中使用相同名称的同一文件。 我想找到最新的修改版,所以我使用这个脚本:
import os
from collections import OrderedDict
home = os.path.expanduser('~/') # path of home, common for al users
result = []
time = {}
name = '.webpyconfig.ini'
for root, dirs, files in os.walk(home):
dirs[:] = [d for d in dirs if not d == '.Trash']
if name in files:
result.append(os.path.join(root, name))
for times in range(0, len(result)):
time[times] = [result[times], os.stat(result[times]).st_mtime]
time = OrderedDict(sorted(time.items(), key=lambda x: x[1]))
maxtime = time[len(time) - 1][1]
maxpath = time[len(time) - 1][0]
for k in range(0, len(time)):
print time[k][1], time[k][0]
print ''
print maxtime, maxpath
结果是:
1448636799.0 /Users/Leo/Desktop/Webpy/.webpyconfig.ini
1448637069.0 /Users/Leo/Desktop/Webpy2/.webpyconfig.ini
1448636937.0 /Users/Leo/Documents/Webpy/.webpyconfig.ini
1448636937.0 /Users/Leo/Documents/Webpy/.webpyconfig.ini
如您所见,订单不正确,因为Webpy2是最新创建的文件。 一些提示?
答案 0 :(得分:1)
您正在将列表存储为值,并按该列表进行排序:
time[times] = [result[times], os.stat(result[times]).st_mtime]
排序键中的 x[1]
是整个列表,包含[path, time]
个值。这意味着您首先按路径排序,而不是修改时间。
你有点过于复杂;只需在os.walk()
循环中添加时间,只需时间:
results = {}
for root, dirs, files in os.walk(home):
dirs[:] = [d for d in dirs if not d == '.Trash']
if name in files:
path = os.path.join(root, name)
results[path] = os.stat(path).m_time
sorted_by_mtime = OrderedDict(sorted(results.items(), key=lambda kv: kv[1]))
for path, time in sorted_by_mtime.items():
print time, path