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 18 Python
在Python中使用itertools模块中的组合函数的教程
Apr 13 Python
Python进程间通信Queue实例解析
Jan 25 Python
python实现淘宝秒杀聚划算抢购自动提醒源码
Jun 23 Python
PyQt5 QSerialPort子线程操作的实现
Apr 21 Python
对IPython交互模式下的退出方法详解
Feb 16 Python
python使用wxpy轻松实现微信防撤回的方法
Feb 21 Python
python实现二级登陆菜单及安装过程
Jun 21 Python
python 计算积分图和haar特征的实例代码
Nov 20 Python
使用Pyhton集合set()实现成果查漏的例子
Nov 24 Python
python-sys.stdout作为默认函数参数的实现
Feb 21 Python
PyInstaller将Python文件打包为exe后如何反编译(破解源码)以及防止反编译
Apr 15 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
phpmyadmin3 安装配置图解教程
2012/03/29 PHP
php的array_multisort()使用方法介绍
2012/05/16 PHP
浅谈php和.net的区别
2014/09/28 PHP
完美解决php 导出excle的.csv格式的数据时乱码问题
2017/02/18 PHP
JS类的封装及实现代码
2009/12/02 Javascript
js弹出窗口之弹出层的小例子
2013/06/17 Javascript
Javascript 拖拽的一些高级的应用(逐行分析代码,让你轻松了拖拽的原理)
2015/01/23 Javascript
javascript批量修改文件编码格式的方法
2015/01/27 Javascript
基于Arcgis for javascript实现百度地图ABCD marker的效果
2015/09/12 Javascript
深入理解nodejs中Express的中间件
2017/05/19 NodeJs
基于jQuery实现手风琴菜单、层级菜单、置顶菜单、无缝滚动效果
2017/07/20 jQuery
vue修改vue项目运行端口号的方法
2017/08/04 Javascript
vuejs+element-ui+laravel5.4上传文件的示例代码
2017/08/12 Javascript
使用Angular CLI生成路由的方法
2018/03/24 Javascript
Node.js HTTP服务器中的文件、图片上传的方法
2019/09/23 Javascript
JS实现秒杀倒计时特效
2020/01/02 Javascript
使用Karma做vue组件单元测试的实现
2020/01/16 Javascript
基于 Vue 的 Electron 项目搭建过程图文详解
2020/07/22 Javascript
antd vue table跨行合并单元格,并且自定义内容实例
2020/10/28 Javascript
JS中锚点链接点击平滑滚动并自由调整到顶部位置
2021/02/06 Javascript
python实现查找excel里某一列重复数据并且剔除后打印的方法
2015/05/26 Python
Python的Flask框架应用调用Redis队列数据的方法
2016/06/06 Python
python绘制圆柱体的方法
2018/07/02 Python
python切片的步进、添加、连接简单操作示例
2019/07/11 Python
Python跑循环时内存泄露的解决方法
2020/01/13 Python
Python Tkinter Entry和Text的添加与使用详解
2020/03/04 Python
pytorch 多分类问题,计算百分比操作
2020/07/09 Python
python 第三方库paramiko的常用方式
2021/02/20 Python
matplotlib之pyplot模块坐标轴标签设置使用(xlabel()、ylabel())
2021/02/22 Python
英国领先的鞋类零售商:Shoe Zone
2018/12/13 全球购物
《最大的“书”》教学反思
2014/02/14 职场文书
药店促销活动策划方案
2014/08/24 职场文书
毕业论文指导教师评语
2014/12/30 职场文书
人事任命书范本
2015/09/21 职场文书
DjangoRestFramework 使用 simpleJWT 登陆认证完整记录
2021/06/22 Python
如何通过简单的代码描述Angular父组件、子组件传值
2022/04/07 Javascript