我对python还比较陌生,我需要得到一个所有一级子目录的列表,这些子目录按上次访问日期倒序排列,我可以在其中爬行。 关键是我正在编写一个cleaning函数,它接收一个包含要释放的兆字节数的变量。然后,它应该遍历所有一级子目录,并根据它们最后访问的日期列出它们。然后函数应该开始删除它们,直到释放所需的兆字节数。你知道吗
到目前为止我的代码是:
import os
def cleanSpace(megs,path="/var/lib/mpd/music/"):
list = []
for root, dir, file in os.walk(path):
this_path = os.path.join(root, dir)
stat = os.stat(this_path)
this_atime = stat.st_atime
this_size = round(stat.st_size/1048576)
list.append([this_path,this_atime,this_size])
sort(list, key=lambda x: x[1], reverse=True)
total_freed = 0
for folder in list:
if total_freed < megs:
#os.unlink(folder[0])
print(folder[0])
total_freed += folder[2]
else:
print("Total freed space:",total_freed)
break
谢谢大家!你知道吗
一个小问题。在我的windows机器上,操作系统路径获取大小会报错号码。你知道吗
更新:见下文
以下是最终代码:
对于文件夹大小,我现在使用函数get\u size()from Calculating a directory's size using Python?
我可以立即看到两个错误:
dir
是一个list
,所以你的意思可能是:但是请注意,
os.walk
将“深入”到所有子目录中-如果您只想获取顶层的子目录,您的意思可能是:没有名为
sort
的内置方法-您的意思是sorted
(或者sort
是在别处定义的吗?)你知道吗(同样根据我的评论,
dir
、list
和file
是您要覆盖的内置变量,因此您应该选择其他变量名)。你知道吗相关问题 更多 >
编程相关推荐