这期内容当中小编将会给大家带来有关利用python如何实现按条件删除系统文件,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
成都创新互联专注于东港网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供东港营销型网站建设,东港网站制作、东港网页设计、东港网站官网定制、微信小程序服务,打造东港网络公司原创品牌,更为您提供东港网站排名全网营销落地服务。按时间删除文件
# importing the required modules import os import shutil import time # main function def main(): # initializing the count deleted_folders_count = 0 deleted_files_count = 0 # specify the path path = "/PATH_TO_DELETE" # specify the days days = 30 # converting days to seconds # time.time() returns current time in seconds seconds = time.time() - (days * 24 * 60 * 60) # checking whether the file is present in path or not if os.path.exists(path): # iterating over each and every folder and file in the path for root_folder, folders, files in os.walk(path): # comparing the days if seconds >= get_file_or_folder_age(root_folder): # removing the folder remove_folder(root_folder) deleted_folders_count += 1 # incrementing count # breaking after removing the root_folder break else: # checking folder from the root_folder for folder in folders: # folder path folder_path = os.path.join(root_folder, folder) # comparing with the days if seconds >= get_file_or_folder_age(folder_path): # invoking the remove_folder function remove_folder(folder_path) deleted_folders_count += 1 # incrementing count # checking the current directory files for file in files: # file path file_path = os.path.join(root_folder, file) # comparing the days if seconds >= get_file_or_folder_age(file_path): # invoking the remove_file function remove_file(file_path) deleted_files_count += 1 # incrementing count else: # if the path is not a directory # comparing with the days if seconds >= get_file_or_folder_age(path): # invoking the file remove_file(path) deleted_files_count += 1 # incrementing count else: # file/folder is not found print(f'"{path}" is not found') deleted_files_count += 1 # incrementing count print(f"Total folders deleted: {deleted_folders_count}") print(f"Total files deleted: {deleted_files_count}") def remove_folder(path): # removing the folder if not shutil.rmtree(path): # success message print(f"{path} is removed successfully") else: # failure message print(f"Unable to delete the {path}") def remove_file(path): # removing the file if not os.remove(path): # success message print(f"{path} is removed successfully") else: # failure message print(f"Unable to delete the {path}") def get_file_or_folder_age(path): # getting ctime of the file/folder # time will be in seconds ctime = os.stat(path).st_ctime # returning the time return ctime if __name__ == '__main__': main()
本文名称:利用python如何实现按条件删除系统文件-创新互联
地址分享:https://www.cdcxhl.com/article18/dsdcdp.html
成都网站建设公司_创新互联,为您提供微信公众号、标签优化、定制开发、网站设计、外贸建站、App设计
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联