python腳本刪除n天之前的文件

管理Linux經常用到python腳本,然後寫了腳本後,經常爲了生成的文件佔用磁盤空間而犯愁,這些寫個函數以方便以後使用:

def rmdaybefore(pfile, days):
    """
    Delete pfile diectory days before files below
    :param pfile: local path
    :param days: before days
    :return: a list os.listdir pfile
    """
    d = 0
    try:
        d = int(days)
    except ValueError,e:
        print "You input the parameters of the days cannot be converted to int."
        sys.exit(1)
    BEDAYS = time.time() - (24 * 60 * 60 * d)
    if os.path.isdir(pfile):
        for f in os.listdir(pfile):
            fname = pfile + os.sep + f
            if os.path.isfile(fname):
                fmtime = os.path.getmtime(fname)
                if fmtime <= BEDAYS:
                    os.remove(fname)
                    return os.listdir(pfile)
    else:
        "You input the parameters of the pfile is not a directory."
        sys.exit(1)
if __name__ == '__main__':
    pfile = r"C:\\Users\\XXX\\Desktop\\html\\"
    for f in rmdaybefore(pfile,0.2):
        print f


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章