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通过websocket与js客户端通信示例分析
Jun 25 Python
python根据开头和结尾字符串获取中间字符串的方法
Mar 26 Python
TensorFlow中权重的随机初始化的方法
Feb 11 Python
小白如何入门Python? 制作一个网站为例
Mar 06 Python
Python实现去除列表中重复元素的方法小结【4种方法】
Apr 27 Python
TensorFlow 合并/连接数组的方法
Jul 27 Python
win8下python3.4安装和环境配置图文教程
Jul 31 Python
Python根据成绩分析系统浅析
Feb 11 Python
PyCharm刷新项目(文件)目录的实现
Feb 14 Python
Python Flask框架实现简单加法工具过程解析
Jun 03 Python
python读取hdfs上的parquet文件方式
Jun 06 Python
scrapy在python爬虫中搭建出错的解决方法
Nov 22 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
将word转化为swf 如同百度文库般阅读实现思路及代码
2013/08/09 PHP
web server使用php生成web页面的三种方法总结
2013/10/28 PHP
php中static和const关键字用法分析
2016/12/07 PHP
Jquery+WebService 校验账号是否已被注册的代码
2010/07/12 Javascript
jquery的Theme和Theme Switcher使用小结
2010/09/08 Javascript
js页面滚动时层智能浮动定位实现(jQuery/MooTools)
2011/08/23 Javascript
首页图片漂浮效果示例代码
2014/06/05 Javascript
深入理解javascript原型链和继承
2014/09/23 Javascript
简介JavaScript中的getUTCFullYear()方法的使用
2015/06/10 Javascript
js实现类似菜单风格的TAB选项卡效果代码
2015/08/28 Javascript
js判断日期时间有效性的方法
2015/10/24 Javascript
JavaScript的Backbone.js框架环境搭建及Hellow world示例
2016/05/07 Javascript
JS清除字符串中重复值的实现方法
2016/08/03 Javascript
jQuery.ajax向后台传递数组问题的解决方法
2017/05/12 jQuery
改变vue请求过来的数据中的某一项值的方法(详解)
2018/03/08 Javascript
javascript设计模式之迭代器模式
2020/01/30 Javascript
vue-cli3访问public文件夹静态资源报错的解决方式
2020/09/02 Javascript
python实现2014火车票查询代码分享
2014/01/10 Python
Python中使用tarfile压缩、解压tar归档文件示例
2015/04/05 Python
Python基于Tkinter模块实现的弹球小游戏
2018/12/27 Python
python tkinter实现屏保程序
2019/07/30 Python
pytorch实现特殊的Module--Sqeuential三种写法
2020/01/15 Python
使用CSS3的rem属性制作响应式页面布局的要点解析
2016/05/24 HTML / CSS
英国最大的网上药品商店:Chemist Direct
2017/12/16 全球购物
Falconeri美国官网:由羊绒和羊毛制成的针织服装
2018/04/08 全球购物
维氏瑞士军刀英国网站:Victorinox英国
2019/07/04 全球购物
编辑硕士自荐信范文
2013/11/27 职场文书
幼儿园优秀教师事迹
2014/02/13 职场文书
老干部工作先进集体事迹材料
2014/05/21 职场文书
119消防日活动总结
2014/08/29 职场文书
城市规划应届生推荐信
2014/09/08 职场文书
2014年学校办公室工作总结
2014/12/19 职场文书
搞笑结婚保证书
2015/05/08 职场文书
2015年行政执法工作总结
2015/05/23 职场文书
七年级写作指导之游记作文
2019/10/07 职场文书
浅谈Python中的正则表达式
2021/06/28 Python