Python:列出一级子目录,按最后一次访问排序

2024-09-28 22:39:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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

Tags: path函数forsizeosrootfolderthis
2条回答

谢谢大家!你知道吗

一个小问题。在我的windows机器上,操作系统路径获取大小会报错号码。你知道吗

更新:见下文

以下是最终代码:

import os
import datetime

def get_size(start_path = '.'):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            total_size += os.path.getsize(fp)
    return total_size

def cleanSpace(megs,path="c:/Users/i/Downloads/"):
    list = []
    for item in os.listdir(path):
        fullitem=os.path.join(path, item)
        if os.path.isdir(fullitem):
            this_path = fullitem
            stat = os.stat(fullitem)
            this_atime = stat.st_atime
            #print("Last access: ",this_atime)
            #print("Last access: ",datetime.datetime.fromtimestamp(this_atime))
            this_size = get_size(fullitem)
            #size in MB
            this_size = round(this_size/1048576)
            list.append([fullitem,this_atime,this_size])
    list = sorted(list, key=lambda x: x[1], reverse=False)
    total_freed = 0
    for folder in list:
        if total_freed < megs:
            #os.unlink(folder[0])
            print(folder[0] + " - size: " + str(folder[2]))
            total_freed = total_freed + folder[2]
        else:
            print("Total freed space (MB):",total_freed)
            break
    if total_freed < megs:
        print("Not enough space freed")

cleanSpace(1100,)

对于文件夹大小,我现在使用函数get\u size()from Calculating a directory's size using Python?

我可以立即看到两个错误:

for root, dir, file in os.walk(path):
    this_path = os.path.join(root, dir)

dir是一个list,所以你的意思可能是:

for root, dir, file in os.walk(path):
    for item in dir:
        this_path = os.path.join(root, item)

但是请注意,os.walk将“深入”到所有子目录中-如果您只想获取顶层的子目录,您的意思可能是:

for item in os.listdir(path):
    if os.path.isdir(item):

没有名为sort的内置方法-您的意思是sorted(或者sort是在别处定义的吗?)你知道吗

(同样根据我的评论,dirlistfile是您要覆盖的内置变量,因此您应该选择其他变量名)。你知道吗

相关问题 更多 >