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实现逆波兰计算表达式实例详解
May 06 Python
Python的消息队列包SnakeMQ使用初探
Jun 29 Python
Python实现PS滤镜的万花筒效果示例
Jan 23 Python
python3第三方爬虫库BeautifulSoup4安装教程
Jun 19 Python
详解Python用户登录接口的方法
Apr 17 Python
简单了解python中对象的取反运算符
Jul 01 Python
Python如何使用k-means方法将列表中相似的句子归类
Aug 08 Python
Pandas —— resample()重采样和asfreq()频度转换方式
Feb 26 Python
如何在Django中使用聚合的实现示例
Mar 23 Python
Django的ListView超详细用法(含分页paginate)
May 21 Python
教你用python控制安卓手机
May 13 Python
在python中读取和写入CSV文件详情
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
php 判断是否是中文/英文/数字示例代码
2013/09/30 PHP
php mysql获取表字段名称和字段信息的三种方法
2016/11/13 PHP
PHP receiveMail实现收邮件功能
2018/04/25 PHP
PHP结合Ffmpeg快速搭建流媒体服务的实践记录
2018/10/31 PHP
JavaScript去除空格的几种方法
2006/10/03 Javascript
解决FLASH需要点击激活的代码
2006/12/20 Javascript
基于jquery的inputlimiter 实现字数限制功能
2010/05/30 Javascript
javascript:文字不间断向左移动的实例代码
2013/08/08 Javascript
JavaScript修改css样式style动态改变元素样式
2013/12/16 Javascript
javascript遍历控件实例详细解析
2014/01/10 Javascript
jquery鼠标放上去显示悬浮层即弹出定位的div层
2014/04/25 Javascript
纯javascript实现简单下拉刷新功能
2015/03/13 Javascript
jQuery+html5实现div弹出层并遮罩背景
2015/04/15 Javascript
javascript中JSON.parse()与eval()解析json的区别
2016/05/19 Javascript
Vue单页应用引用单独的样式文件的两种方式
2018/03/30 Javascript
vue 中引用gojs绘制E-R图的方法示例
2018/08/24 Javascript
axios使用拦截器统一处理所有的http请求的方法
2018/11/02 Javascript
javascript设计模式 ? 职责链模式原理与用法实例分析
2020/04/16 Javascript
JavaScript onclick事件使用方法详解
2020/05/15 Javascript
解决vue-cli输入命令vue ui没效果的问题
2020/11/17 Javascript
[39:52]2018DOTA2亚洲邀请赛 4.3 突围赛 EG vs Newbee 第一场
2018/04/04 DOTA
[02:22]2018DOTA2亚洲邀请赛VG赛前采访
2018/04/03 DOTA
PyQt5每天必学之创建窗口居中效果
2018/04/19 Python
Python爬虫常用库的安装及其环境配置
2018/09/19 Python
python 实现屏幕录制示例
2019/12/23 Python
使用python画出逻辑斯蒂映射(logistic map)中的分叉图案例
2020/12/11 Python
python des,aes,rsa加解密的实现
2021/01/16 Python
HTML5语音识别标签写法附图
2013/11/18 HTML / CSS
大学本科生的个人自我评价
2013/12/09 职场文书
美容院营销方案
2014/03/05 职场文书
司机职责范本
2014/03/08 职场文书
搞笑的获奖感言
2014/08/16 职场文书
2014年社区宣传工作总结
2014/12/02 职场文书
2015年上半年物业工作总结
2015/03/30 职场文书
又涨知识了,自律到底多重要?
2019/06/27 职场文书
用 Python 定义 Schema 并生成 Parquet 文件详情
2021/09/25 Python