Use Python to help you clean windows trash

Source: Internet
Author: User
Tags prefetch
Objective

Everyone should have some experience, in the Windows system used for a long time will produce some "junk" files. These files are the temporary files of the program, some operation records or logs, etc. The accumulation of garbage over time, resulting in reduced available space, too much file fragmentation, the speed of the system will be affected.

Mac and Linux systems do not have such problems, so they are only available for Windows

Knowledge overview

Some cache files can improve the execution speed of the program, such as caching cookies, using record recent, pre-reading prefetch, and so on. So cleaning up temporary files does not mean that the system will run faster, and sometimes it may slow down.

What are the main junk files and folders in Windows computer?

System disk%system% file type:

"Temp file (*.tmp)"

"Temp file (*._MP)"

"Log file (*.log)"

"Temporary Help file (*.gid)"

"Disk check file (*.chk)"

"Temporary backup file (*.old)"

"Excel backup file (*.xlk)"

"Temporary backup file (*.bak)"

User Directory%userprofile% under folder

"COOKIE" Cookies\*.*

"File Usage Record" Recent\*.*

"IE temp file" temporary Internet files\*.*

"Temporary Files folder" Temp\*.*

Windows Directory%windir% folder

Pre-read Data folder Prefetch\*.*

"Temp File" Temp\*.*

Get file Address

The operation requires an OS module, such as obtaining a working directory:

Import Osprint os.getcwd () # ' E:\\pythonsource\\leanr_py '

Switch working directory:

Os.chdir (' D://wamp ') print os.getcwd () # ' D:\\wamp '

Get system drive Letter:

os.environ[' systemdrive '] # ' C: '

Get the User directory:

os.environ[' UserProfile '] # ' C:\\users\\administrator '

Get the Windows directory:

os.environ[' windir '] # ' C:\\Windows '

Traverse Directory

To traverse a folder, you need to use the Os.walk (Top,topdown=true,onerror=none)

The parameter top represents the path of the top-level directory that needs to be traversed.

The default value for parameter topdown is "True" to first return files in the top-level directory, and then to traverse files in subdirectories. When the value of Topdown is "False", it means traversing the files in the subdirectory before returning to the files in the top-level directory.

The default value of parameter onerror is "None", which means that errors are ignored when the file is traversed. If it is not empty, a custom function tip error message is provided after continuing the traversal or throwing an exception to abort the traversal.

Return value: The function returns a tuple containing three elements. The three elements are: the path name of each traversal, the path under the directory list, and the list of files in the directory.

For roots, dirs, files in Os.walk (' D://wamp ', topdown=false) # Roots folder path, dirs Folder list under that directory, files file list print roots # d://w AMP Print dirs # [' Bin ', ' www ', ' alias '] print files # [' wampmanage.conf ', ' 1.txt ']

Determine if the junk file

Os.path.splitext () can cut the file name

Extension = Os.path.splitext (R ' aaa\bbb\ccc.ddd ') # (' AAA\\BBB\\CCC ', '. ddd ') if extension[1] in ['. tmp ', '. Bak ']: print ' is Junk file '

deleting files

Deleting a file is called a different function than deleting a folder.

# Delete File Os.remove (' D:temporary/test/test.txt ') # Delete folder Os.rmdir (' D:temporary/test/empty ')

Os.rmdir can only delete empty folders, if the folder is not empty, it will be an error. So you should use:

Shutil.rmtree (' d:/dir1/dir2/aaa ')

If the file is running or protected and the current account does not have sufficient permissions, the deletion will error.

The final collation of the delete function is:

def del_dir_or_file (Root): try:  if Os.path.isfile (root):   # Delete file   os.remove (root)   print ' file: ' + root + ' Removed '  elif os.path.isdir (root):   # Delete Folder   Shutil.rmtree (root)   print ' directory: ' + root + ' removed ' Except Windowserror:  print ' failure: ' + root + ' can ' t remove

Get File size

# Show folder (path) size, Unit biteos.path.getsize (' D://temporary/test ') # 4096 # File size os.path.getsize (' D://temporary/test/aaa.txt ' ) # 135

Complete program

Note: Because of the file deletion involved, be sure to repeatedly confirm the code before you start, in case any important files are deleted.

Always Confirm!!!

Always Confirm!!!

Always Confirm!!!

Import Osimport Jsonimport shutildel_extension = {'. tmp ': ' temp file ', '. _mp ': ' Temporary file _mp ', '. Log ': ' Log file ', '. Gid ': ' Temporary Help file ', '. Chk ': ' Disk check file ', '. Old ': ' Temporary backup file ', '. Xlk ': ' Excel backup file ', '. Bak ': ' Temporary backup file Bak '} del_userprofile = [' Cookies ', ' recent ', ' Tempo Rary Internet Files ', ' temp ']del_windir = [' prefetch ', ' temp '] # get system disk Sys_drive = os.environ[' systemdrive '] + ' \ \ ' # Get user Directory User_profile = os.environ[' userprofile ']# get Windows directory win_dir = os.environ[' windir '] # Get current path os.getcwd () ' E:\\software\ \python27 ' # jump to the specified file directory os.chdir (' D://wamp ') # Get the system drive letter os.environ[' systemdrive '] ' C: ' # Get the user directory os.environ[' userprofile ' C:\\users\\administrator ' # Get Windows directory os.environ[' windir ' ' C:\\Windows ' def del_dir_or_file (root): Try:if    Os.path.isfile (Root): # delete file Os.remove (root) print ' file: ' + root + ' removed ' elif os.path.isdir (root): # Delete Folder Shutil.rmtree (root) print ' directory: ' + root + ' removed ' except Windowserror:print ' failure: ' + root + ' can ' t Remove "# byte bytes conversion kb\m\gdef formatsize(bytes): try:bytes = float (bytes) KB = bytes/1024 except:print ("Incoming byte is not formatted") return "Error" if kb >= 1024:m = kb/1024 if M >= 1024:g = m/1024 return "%FG"% (G) else:return "%FM"% (M) else:return "%fkb"% (KB) CL Diskclean (object): Def __init__ (self): Self.del_info = {} self.del_file_paths = [] self.total_size = 0 for k,v in Del_extension.items (): self.del_info[k] = dict (name = V, count = 0) def scan (self): for roots, dirs, files in Os.walk (User_profile, Topdown=false): # generates and expands a directory tree rooted in root, with parameters Topdown set to expand from the bottom to the top for File_item in Files: # Get extension fi Le_extension = Os.path.splitext (File_item) [1] # Print os.path.join (roots, File_item) if file_extension in Self.del_i NFO: # file full path File_full_path = Os.path.join (Roots, File_item) Self.del_file_paths.append (File_full_path) s elf.del_info[file_extension][' count '] + = 1 self.total_size + os.path.getsize (File_full_path) def Show (self): print Json.dumps (Self.del_info, indent=4, ensure_ascii=false) print ' Delete can save:%s space '% formatsize (self.total_size) def delete_files (self): for I in self . Del_file_paths:del_dir_or_file (i) if __name__ = = ' __main__ ': cleaner = Diskclean () Cleaner.scan () cleaner.show () If_de L = raw_input (' delete y/n: ') if If_del = = ' Y ': cleaner.delete_files ()

Summarize

Recently looking at some of the content of the QT interface. Can be combined to do a graphical interface of the program. The above is the entire content of this article, I hope that the content of this article on everyone's study or work can bring certain help, if there is doubt you can message exchange.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.