本文概述
定期手动清理文件系统是不好的。使它们自动化!
可能会想到, 手动删除文件和文件夹并不是一项令人兴奋的任务。使它们自动化是有意义的。
Python来了, 使我们的生活更轻松。 Python是一种出色的脚本编程语言。我们将利用Python毫无障碍地完成我们的任务。首先, 你应该知道为什么Python是一个不错的选择。
- Python是用于自动执行任务的最受人喜爱的语言
- 与其他编程语言相比, 代码更少
- Python与所有操作系统兼容。你可以在Windows, Linux和Mac中运行相同的代码。
- Python有一个名为os的模块, 可以帮助我们与操作系统进行交互。我们将使用该模块来完成删除文件的自动化操作。
我们可以使用Python替换所有烦人或重复的系统任务。如果你了解Python, 那么编写脚本来完成特定的系统任务就很困难。让我们看一下以下用例。
注意:以下内容已在Python 3.6+上进行了测试
删除X天之前的文件/文件夹
通常, 你不需要旧日志, 并且定期需要清理它们以提供存储空间。它可以是任何东西, 而不仅仅是日志。
os模块中有一个称为stat的方法, 该方法提供了上次访问(st_atime), 修改(st_mtime)和元数据修改(st_ctime)时间的详细信息。自该纪元以来, 所有方法都以秒为单位返回时间。你可以在此处找到有关纪元的更多详细信息。
我们将使用一种称为os.walk(path)的方法遍历文件夹的子文件夹。
请按照以下步骤, 根据天数为删除文件/文件夹编写代码。
- 导入模块时间, 操作系统, 关机
- 设置变量的路径和天数
- 使用time.time()方法将天数转换为秒
- 使用os.path.exists(path)模块检查路径是否存在
- 如果该路径存在, 则获取该路径中存在的文件和文件夹的列表, 包括子文件夹。使用方法os.walk(path), 它将返回一个包含文件夹, 文件和子文件夹的生成器
- 通过使用os.path.join()方法连接当前路径和文件/文件夹名称来获取文件或文件夹的路径
- 使用属性st_ctime从os.stat(path)方法获取ctime
- 将ctime与我们之前计算的时间进行比较
- 如果结果大于所需的用户天数, 请检查它是文件还是文件夹。如果是文件, 请使用os.remove(path), 否则请使用shutil.rmtree()方法
- 如果路径不存在, 则显示找不到打印消息
让我们详细查看代码。
# 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()
你需要根据需要在上面的代码中调整以下两个变量。
days = 30
path = "/PATH_TO_DELETE"
删除大于X GB的文件
让我们搜索大于特定大小的文件并将其删除。它类似于上面的脚本。在上一个脚本中, 我们将age作为参数, 现在将size作为删除的参数。
# importing the os module
import os
# function that returns size of a file
def get_file_size(path):
# getting file size in bytes
size = os.path.getsize(path)
# returning the size of the file
return size
# function to delete a file
def remove_file(path):
# deleting the file
if not os.remove(path):
# success
print(f"{path} is deleted successfully")
else:
# error
print(f"Unable to delete the {path}")
def main():
# specify the path
path = "ENTER_PATH_HERE"
# put max size of file in MBs
size = 500
# checking whether the path exists or not
if os.path.exists(path):
# converting size to bytes
size = size * 1024 * 1024
# traversing through the subfolders
for root_folder, folders, files in os.walk(path):
# iterating over the files list
for file in files:
# getting file path
file_path = os.path.join(root_folder, file)
# checking the file size
if get_file_size(file_path) >= size:
# invoking the remove_file function
remove_file(file_path)
else:
# checking only if the path is file
if os.path.isfile(path):
# path is not a dir
# checking the file directly
if get_file_size(path) >= size:
# invoking the remove_file function
remove_file(path)
else:
# path doesn't exist
print(f"{path} doesn't exist")
if __name__ == '__main__':
main()
调整以下两个变量。
path = "ENTER_PATH_HERE"
size = 500
删除具有特定扩展名的文件
在某些情况下, 你想按文件的扩展名类型删除文件。假设是.log文件。我们可以使用os.path.splitext(path)方法找到文件的扩展名。它返回一个元组, 其中包含文件的路径和扩展名。
# importing os module
import os
# main function
def main():
# specify the path
path = "PATH_TO_LOOK_FOR"
# specify the extension
extension = ".log"
# checking whether the path exist or not
if os.path.exists(path):
# check whether the path is directory or not
if os.path.isdir(path):
# iterating through the subfolders
for root_folder, folders, files in os.walk(path):
# checking of the files
for file in files:
# file path
file_path = os.path.join(root_folder, file)
# extracting the extension from the filename
file_extension = os.path.splitext(file_path)[1]
# checking the file_extension
if extension == file_extension:
# deleting the file
if not os.remove(file_path):
# success message
print(f"{file_path} deleted successfully")
else:
# failure message
print(f"Unable to delete the {file_path}")
else:
# path is not a directory
print(f"{path} is not a directory")
else:
# path doen't exist
print(f"{path} doesn't exist")
if __name__ == '__main__':
# invoking main function
main()
不要忘记更新上面代码中的path和extension变量, 以满足你的要求。
我建议在NON PRODUCTION环境中测试脚本。对结果满意后, 你可以通过cron(如果使用Linux)进行计划, 以定期运行它以进行维护工作。 Python非常适合完成这些工作, 如果对学习做更多的事情感兴趣, 请查看Udemy课程。
评论前必须登录!
注册