Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize automatic sorting of documents in batches by Python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "Python how to automatically organize files in batches". In daily operation, I believe that many people have doubts about how to achieve automatic sorting of documents in batches by Python. The editor has consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "how to automatically organize documents in batches by Python". Next, please follow the editor to study!

In order to implement such a gadget, let's imagine the following functions.

1. You can customize all the files that need to be sorted out under a certain path.

2. By default, the file suffix is used as the folder name of the same kind of files, and partners with other ideas can extend it by themselves.

Import the used python module into the code block.

Import os # File / folder Application Operations import shutil # move files import logging # use log logging to print logs

Select the original file directory to be sorted out.

The following is the effect map after finishing, according to the file type to sort out various documents.

Add the log printing module to the code block, where the log printing chooses the logging module.

Logger = logging.getLogger ('automatic induction file') # log name logging.basicConfig (format='% (asctime) s% (filename) s [line:% (lineno) d]% (levelname) s% (message) s') # log print format logger.setLevel (logging.DEBUG) # log print level

The following is the full implementation of the documented code block, with comments on the main parts.

Dir = input ('Please enter the file directory to be sorted out:\ n') # the file path to be sorted out is if os.path.isdir (dir): logger.info (' current directory ['+ dir +'] checked successfully!) Paths = [] for file_path, dir_names, file_names in os.walk (rushing'+ dir): for file_name in file_names: try: file_name_path = os.path.join (file_path, file_name) dir_ = file_name.split ('.') [1] new_file_name_path = os.path.join (dir Dir_) # verify whether the new folder already exists if os.path.isdir (new_file_name_path): # directly move the file shutil.move (file_name_path) New_file_name_path) else: # move the file os.mkdir (new_file_name_path) shutil.move (file_name_path, new_file_name_path) paths.append (os.path.join (new_file_name_path) after creating the folder File_name)) except: logger.error ('['+ file_name_path +'] Mobile exception occurred Execute the next!') For path in paths: logger.info ('Mobile completed file:' + str (path)) else: logger.error ('the folder or directory entered does not exist!')

The above is the implementation part of all the code blocks of the automatic collation file. When you use it, you can copy the code blocks to your own development tools and start them directly.

Advanced level

When the files are in different paths, how to achieve batch management? the following is the implementation code, which can be referred to.

Import osimport globimport shutil'''@Author: huny@date: 2020.12.06@function: filing''class FileType (): def _ _ init__ (self): self.filetype = {"Picture": [".jpeg", ".jpg", ".tiff", ".gif", ".bmp", ".png", ".bpg", "svg", ".heif", ".psd"] "Video": [.avi "," .flv "," .wmv "," .mov "," .mp4 "," .webm "," .vob "," .mng "," .qt "," .mpg "," .mpeg "," .3gp "," .mkv "]," audio ": [" .aac "," .aa "," .aac "," .dvf "," .m4a "). ".m4b", ".m4p", ".mp3", ".msv", ".ogg", ".oga", ".raw", ".vox", ".wav", ".wma"], "documents": [".oxps", ".epub", ".pages", ".docx", ".doc", ".fdf", ".ods", ".odt", ".pwi", ".xsn" ".xps", ".dotx", ".docm", ".dox", ".rvg", ".rtf", ".rtfd", ".wpd", ".xls", ".xlsx", ".ppt", ".pptx", ".csv", ".pdf", ".md", ".xmind"], "compressed files": [".a", ".ar", ".cpio", ".iso" ".tar", ".gz", ".rz", ".7z", ".dmg", ".rar", ".xar", ".zip"], "text": [".txt", ".in", ".out", ".json", "xml", ".log"], "program script": [".py", ".html5", ".html", ".htm" ".xhtml", ".c", ".cpp", ".java", ".css", ".sql"], "executable program": [".exe", ".bat", ".lnk"], "font file": [".ttf", ".OTF", ".WOFF", ".EOT"]} def JudgeFile (self, pathname): Type in self.filetype.items (): if pathname in type: return name return "unable to determine type file" class DeskTopOrg (object): def _ _ init__ (self): self.filetype = FileType () def Organization (self): filepath = input ("Please enter the folder path to be sorted out:") paths = glob.glob (filepath + "/ *. *") print ('paths-- >') Paths) for path in paths: try: if not os.path.isdir (path): file = os.path.splitext (path) filename,type = file print ('type-- >', type) print ("filename-- >", filename) print ('path-- >' Path) dir_path = os.path.dirname (path) print ('dir_path-- >', dir_path) savePath = dir_path +'/ {} '.format (self.filetype.JudgeFile (type)) print (' savePath-- >', savePath) if not os.path.exists (savePath): os.mkdir (savePath) shutil.move (path SavePath) else: shutil.move (path, savePath) except FileNotFoundError: pass print ("Program execution is over!") If _ _ name__ ='_ _ main__': try: while True: desktopOrg = DeskTopOrg () desktopOrg.Organization () print ("- > your file has been sorted out.") A = input ('- > Please press enter to exit:') if a =': break except BaseException: print ("ERROE: wrong path or duplicate document")

In this way, you are free to sort out the path you want.

At this point, the study on "how to automatically organize files in batches by Python" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report