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

按时间删除文件

# 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 删除文件的资料请关注我们其它相关文章!

(0)

相关推荐

  • 利用python在大量数据文件下删除某一行的例子

    python修改大数据文件时,如果全加载到内存中,可能会导致内存溢出.因此可借用如下方法,将分件分段读取修改. with open('file.txt', 'r') as old_file: with open('file.txt', 'r+') as new_file: current_line = 0 # 定位到需要删除的行 while current_line < (3 - 1): #(del_line - 1) old_file.readline() current_line += 1

  • python从zip中删除指定后缀文件(推荐)

    一,说明 环境:python2 用到的模块 os zipfile shutil 程序功能:从zip中删除指定后缀的文件,然后再自动压缩 函数说明: DelFileInZip(path,suffix) path: zip文件的全路径 suffix: 指定的文件后缀 二,源码 import shutil import zipfile import os from shutil import * def UnZipFile(zip_src, dst_dir):#解压函数,将zip_src解压到dst_

  • python如何删除文件、目录

    本文讲述了python实现删除文件与目录的方法.分享给大家供大家参考.具体实现方法如下: os.remove(path) 删除文件 path. 如果path是一个目录, 抛出 OSError错误.如果要删除目录,请使用rmdir(). remove() 同 unlink() 的功能是一样的 在Windows系统中,删除一个正在使用的文件,将抛出异常.在Unix中,目录表中的记录被删除,但文件的存储还在. #使用os.unlink()和os.remove()来删除文件 #!/user/local/

  • python删除文件夹下相同文件和无法打开的图片

    前天不小心把硬盘格式化了,丢了好多照片,后来用Recuva这款软件成功把文件恢复过来,可是恢复的文件中有好多重复的文件和无法打开的图片,所以写了两个python的小程序用来解决这个问题 删除相同文件: #coding=utf-8 import os import os.path import Image import hashlib def get_md5(filename): m = hashlib.md5() mfile = open(filename, "rb") m.updat

  • 基于python实现删除指定文件类型

    Python 是一个高层次的结合了解释性.编译性.互动性和面向对象的脚本语言. Python 的设计具有很强的可读性,相比其他语言经常使用英文关键字,其他语言的一些标点符号,它具有比其他语言更有特色语法结构. Python 是一种解释型语言: 这意味着开发过程中没有了编译这个环节.类似于PHP和Perl语言. Python 是交互式语言: 这意味着,您可以在一个 Python 提示符 >>> 后直接执行代码. Python 是面向对象语言: 这意味着Python支持面向对象的风格或代码封

  • python删除本地夹里重复文件的方法

    上次的博文主要说了从网上下载图片,于是我把整个笑话网站的图片都拔下来了,但是在拔取的图片中有很多重复的,比如说页面的其他图片.重复发布的图片等等.所以我又找了python的一些方法,写了一个脚本可以删除指定文件夹里重复的图片. 一.方法和思路 1.比对文件是否相同的方法:hashlib库里提供了获取文件md5值的方法,所以我们可以通过md5值来判定是否图片相同 2.对文件的操作:os库里有对文件的操作方法,比如:os.remove()可以删除指定的文件, os.listdir()可以通过指定文件

  • python 两种方法删除空文件夹

    第一种方法: import os def delete_gap_dir(dir): if os.path.isdir(dir): for d in os.listdir(dir): #print('1',os.path.join(dir, d)) path = os.path.join(dir, d) if os.path.isdir(path) and not path.endswith('pic_neg'): delete_gap_dir(path) if not os.listdir(di

  • Python彻底删除文件夹及其子文件方式

    我就废话不多说了,直接上代码吧! #coding:utf-8 import os import stat import shutil #filePath:文件夹路径 def delete_file(filePath): if os.path.exists(filePath): for fileList in os.walk(filePath): for name in fileList[2]: os.chmod(os.path.join(fileList[0],name), stat.S_IWR

  • python如何删除文件中重复的字段

    本文实例为大家分享了python如何删除文件中重复字段的具体代码,供大家参考,具体内容如下 原文件内容放在list中,新文件内容按行查找,如果没有出现在list中则写入第三个文件中. import csv filetxt1 = 'E:/gg/log/log1.txt' filecsv1 = 'E:/gg/log/log1.csv' filecsv2 = 'E:/gg/log/log2.csv' filecsv3 = 'E:/gg/log/log3.csv' class operFileCsv()

  • python 解压、复制、删除 文件的实例代码

    压缩复制删除文件基于python语言怎么操作呢,压缩文件有四种格式:zip.rar.tar.tar.gz,在压缩过程中也容易出现很多问题,今天小编通过代码给大家详解,具体内容如下所示: 一.python3解压文件 1.python 解压文件代码示例 如下代码主要实现zip.rar.tar.tar.gz四种格式的压缩文件的解压 def unzip_file(src_file, dst_dir=None, unzipped_files=None, del_flag=True): ""&qu

  • python怎么删除缓存文件

    python删除缓存文件的方法: 首先输入"find.-name '__pycache__' -type d -exec rm -rf {} \"命令删除所有子目录: 然后输入"find.-name "*.pyc""命令删除.pyc文件即可. 删除当前目录下的所有__pycache__子目录 find . -name '__pycache__' -type d -exec rm -rf {} \ 删除当前目录下所有.pyc文件 find . -n

  • Python实现拷贝/删除文件夹的方法详解

    本文实例讲述了Python实现拷贝 删除文件夹的方法.分享给大家供大家参考,具体如下: 1. 拷贝文件夹 from shutil import copytree, ignore_patterns copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*')) 注:shutil.copytree实现 def copytree(src, dst, symlinks=False, ignore=None): names =

  • python删除文件、清空目录的实现方法

    Python os.remove() 方法 os.remove() 方法用于删除指定路径的文件.如果指定的路径是一个目录,将抛出OSError. 在Unix, Windows中有效 以下实例演示了 remove() 方法的使用: #!/usr/bin/python # -*- coding: UTF-8 -*- import os, sys # 列出目录 print "目录为: %s" %os.listdir(os.getcwd()) # 移除 os.remove("aa.t

  • python删除某个目录文件夹的方法

    python删除某个目录文件夹及文件的方法: #!/usr/bin/env python import os import shutil delList = [] delDir = "/home/test" delList = os.listdir(delDir ) for f in delList: filePath = os.path.join( delDir, f ) if os.path.isfile(filePath): os.remove(filePath) print f

随机推荐