Use the python program to clean up windows spam and pythonwindows

Source: Internet
Author: User

Use the python program to clean up windows spam and pythonwindows

Preface

Everyone should have some experience that some "junk" files will be generated after a long time in windows. Some of these files are temporary files of the program, some are operation records or logs. The accumulation of garbage over time results in reduced available space and excessive file fragments, which affects the running speed of the system.

Mac and Linux systems do not have such problems, so they are only applicable to windows

Knowledge Overview

Some cached files can speed up program execution, such as cache cookies, use recent records, and pre-read prefetch. Therefore, clearing temporary files does not mean that the system runs faster or sometimes slows down.

What are the main junk files and folders in windows?

File Type in system Disk % system %:

[Temporary file (*. tmp )]

[Temporary 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 % folder

[COOKIE] cookies \*.*

[File Usage Record] recent \*.*

[IE Temporary Files] Temporary Internet Files \*.*

[Temporary file folder] Temp \*.*

Windows Directory % windir % folder

[Pre-read data folder] prefetch \*.*

[Temporary file] temp \*.*

Get file address

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

import osprint os.getcwd() # 'E:\\PythonSource\\leanr_py'

Switch the working directory:

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

Obtain the system drive letter:

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

Get user directory:

os.environ['userprofile'] # 'C:\\Users\\Administrator'

Obtain the Windows directory:

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

Traverse directories

To traverse folders, you need to useos.walk(top,topdown=True,onerror=None)

  • The top parameter indicates the path of the top-level directory to be traversed.
  • The default value of the topdown parameter is "True", indicating that the files under the top-level directory are returned first, and then the files in the subdirectories are traversed. If the value of topdown is "False", the system first traverses the files in the subdirectory and then returns the files in the top-level directory.
  • The default onerror parameter is "None", indicating that the file duration error is ignored. If it is not empty, a user-defined function will be provided with an error message to continue traversal or throw an exception to stop traversal.
  • Returned value: the function returns a triple containing three elements. These three elements are: the path name for each traversal, the subdirectory list under the path, and the file list under the directory.
For roots, dirs, files in OS. walk ('d: // wamp', topdown = False) # The path of the roots folder, the folder list under the directory dirs, and the file list print roots # d: // wamp print dirs # ['bin', 'www ', 'Alias'] print files # ['wampmanage. conf ', '1.txt']

Determine whether a spam file is used

os.path.splitext() You can cut file names.

Extension = OS. path. splitext (r'aaa \ bbb \ ccc. ddd ') # ('aaa \ bbb \ ccc ','. ddd ') if extension [1] in ['. tmp ','. bak ']: print' is a spam File'

Delete an object

Deleting a file is different from deleting a folder.

# Delete file OS. remove ('d: temporary/test/test.txt ') # Delete the folder OS. rmdir ('d: temporary/test/empty ')

OS. rmdir can only delete empty folders. If the folder is not empty, an error is returned. So we should use:

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

If the file is running or protected, and the current account does not have sufficient permissions, an error is returned when the file is deleted.

Finally, the deletion function is:

Def del_dir_or_file (root): try: if OS. path. isfile (root): # delete the file OS. remove (root) print 'file: '+ root + 'removed' elif OS. path. isdir (root): # Delete the folder shutil. rmtree (root) print 'Directory: '+ root + 'removed' handle t WindowsError: print 'failure:' + root + "can't remove"

Get File Size

# Display the folder (PATH) size, in biteos. path. getsize ('d: // temporary/test') #4096 # file size OS. path. getsize ('d: // temporary/test/aaa.txt ') #135

Complete procedure

Note: Due to the file deletion operation, please confirm the code repeatedly before you start the operation, in case any important files are deleted.

Be sure to confirm !!!

Be sure to confirm !!!

Be sure to confirm !!!

Import osimport jsonimport shutildel_extension = {'. tmp ': 'temporary 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 ', 'temporary Internet Files', 'temp '] del_windir = ['prefetch ', 'temp '] # obtain the system disk SYS_DRIVE = OS. environ ['systemdrive '] +' \ '# obtain the USER_PROFILE = OS. environ ['userprofile '] # obtain the Windows directory WIN_DIR = OS. environ ['windir'] # obtain the current path OS. getcwd () 'e: \ Software \ python27' # Jump to the specified file directory OS. chdir ('d: // wamp') # obtain the OS. environ ['systemdrive '] 'C:' # obtain the user directory OS. environ ['userprofile '] 'C: \ Users \ Administrator' # obtain the Windows directory OS. environ ['windir'] 'C: \ Windows 'def del_dir_or_file (root): try: if OS. path. isfile (root): # delete the file OS. remove (root) print 'file: '+ root + 'removed' elif OS. path. isdir (root): # Delete the folder shutil. rmtree (root) print 'Directory: '+ root + 'removed' handle T WindowsError: print 'failure: '+ root + "can't remove" # convert byte bytes kb \ m \ gdef formatSize (bytes): try: bytes = float (bytes) kb = bytes/1024 bytes t: print ("the input byte format is incorrect") 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) class 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): # generate and expand the directory tree with root as the root directory. The topdown setting of the parameter ranges from the underlying layer to the top layer for file_item in files: # obtain the extension file_extension = OS. path. splitext (file_item) [1] # print OS. path. join (roots, file_item) if file_extension in self. del_info: # complete file path file_full_path = OS. path. join (roots, file_item) self. del_file_paths.append (file_full_path) self. 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 'deletion 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_del = raw_input ('delete y/n: ') if if_del = 'y': cleaner. delete_files ()

Summary

Recently I am reading some content on the qt interface. A program with a graphical interface can be combined. The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.

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.