python 删除系统中的文件(按时间,大小,扩展名)


Posted in Python onNovember 19, 2020

按时间删除文件

# 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"

按大小删除文件

# 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变量,以满足您的要求。

以上就是python 删除系统中的文件的详细内容,更多关于python 删除文件的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
python实现定制交互式命令行的方法
Jul 03 Python
Python中的生成器和yield详细介绍
Jan 09 Python
Python实现合并同一个文件夹下所有txt文件的方法示例
Apr 26 Python
python 实现求解字符串集的最长公共前缀方法
Jul 20 Python
详解python pandas 分组统计的方法
Jul 30 Python
在pycharm中为项目导入anacodna环境的操作方法
Feb 12 Python
python GUI库图形界面开发之PyQt5信号与槽基本操作
Feb 25 Python
解决python便携版无法直接运行py文件的问题
Sep 01 Python
django数据模型中null和blank的区别说明
Sep 02 Python
利用Python发送邮件或发带附件的邮件
Nov 12 Python
pytorch中的model.eval()和BN层的使用
May 22 Python
python数字图像处理之图像自动阈值分割示例
Jun 28 Python
Python并发爬虫常用实现方法解析
Nov 19 #Python
python实现文件分片上传的接口自动化
Nov 19 #Python
Python类class参数self原理解析
Nov 19 #Python
Python爬虫如何破解JS加密的Cookie
Nov 19 #Python
python制作一个简单的gui 数据库查询界面
Nov 19 #Python
解决python3中os.popen()出错的问题
Nov 19 #Python
Python中return函数返回值实例用法
Nov 19 #Python
You might like
ajax 的post方法实例(带循环)
2011/07/04 PHP
PHP常用正则表达式集锦
2014/08/17 PHP
php+ajax实现文章自动保存的方法
2014/12/30 PHP
Zend Framework动作助手Redirector用法实例详解
2016/03/05 PHP
Yii2框架实现数据库常用操作总结
2017/02/08 PHP
PHP编程计算两个时间段是否有交集的实现方法(不算边界重叠)
2017/05/30 PHP
javascript引导程序
2008/10/26 Javascript
jquery异步循环获取功能实现代码
2010/09/19 Javascript
Jquery解析Json格式数据过程代码
2014/10/17 Javascript
jquery文档操作wrap()方法实例简述
2015/01/10 Javascript
js实现鼠标悬停图片上时滚动文字说明的方法
2015/02/17 Javascript
JS实现让访问者自助选择网页文字颜色的方法
2015/02/24 Javascript
JQuery实现动态添加删除评论的方法
2015/05/18 Javascript
ionic组件ion-tabs选项卡切换效果实例
2016/08/27 Javascript
jQuery validate插件功能与用法详解
2016/12/15 Javascript
Angular实现表单验证功能
2017/11/13 Javascript
微信小程序如何获取用户手机号
2018/01/26 Javascript
vue+jquery+lodash实现滑动时顶部悬浮固定效果
2018/04/28 jQuery
vue v-model动态生成详解
2018/06/30 Javascript
vue实现文件上传功能
2018/08/13 Javascript
Vue 中对图片地址进行拼接的方法
2018/09/03 Javascript
详解Vue中watch的详细用法
2018/11/28 Javascript
vue项目中使用fetch的实现方法
2019/04/25 Javascript
JavaScript静态作用域和动态作用域实例详解
2019/06/17 Javascript
[15:07]lgd_OG_m2_BP
2019/09/10 DOTA
Python读取properties配置文件操作示例
2018/03/29 Python
django中模板的html自动转意方法
2018/05/27 Python
python实现一组典型数据格式转换
2018/12/15 Python
详解python爬虫系列之初识爬虫
2019/04/06 Python
解决Python3下map函数的显示问题
2019/12/04 Python
马来西亚最热门的在线时尚商店:FashionValet
2018/11/11 全球购物
JPA面试常见问题
2016/11/14 面试题
好的自荐信包括什么内容
2013/11/07 职场文书
大一军训感言
2014/01/09 职场文书
综合素质自我评价怎么写
2014/09/14 职场文书
初中生活随笔
2015/08/15 职场文书