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

What are the Python utility scripts?

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly explains "what are the practical scripts of Python". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what are the practical scripts for Python"?

1. Solve the problem of unzip garbled codes under linux. Import osimport sysimport zipfileimport argparses ='\ x1b [% d % dm%s\ x1b [0m 'def unzip (path): file = zipfile.ZipFile (path) "r") if args.secret: file.setpassword (args.secret) for name in file.namelist (): try: utf8name=name.decode ('gbk') pathname = os.path.dirname (utf8name) except: utf8name=name pathname = os.path.dirname (utf8name) # print s% (1,92,' > > extracting:') Utf8name # pathname = os.path.dirname (utf8name) if not os.path.exists (pathname) and pathname! = "": os.makedirs (pathname) data = file.read (name) if not os.path.exists (utf8name): try: fo = open (utf8name W) fo.write (data) fo.close except: pass file.close () def main (argv): # for argparse P = argparse.ArgumentParser (description=' solves unzip garbled') p.add_argument ('xxx' Type=str, nargs='*',\ help=' command object.') P.add_argument ('- slots,'--secret', action='store',\ default=None, help=' password') global args args = p.parse_args (argv [1:]) xxx = args.xxx for path in xxx: if path.endswith ('.zip'): if os.path.exists (path): print s% (1,97,'+ + unzip:') Path unzip (path) else: print s% (1,91,'! File doesn\ 't exist.'), path else: print s% (1,91,'! File isn\'t a zip file.'), pathif _ _ name__ = ='_ main__': argv = sys.argv main (argv) 2. Count the number of lines of code in the current root directory # coding=utf-8import osimport time# set the root directory basedir ='. / 'filelists = [] # specify the file type to be counted whitelist = [' cpp','h'] # traverse the file and recursively traverse all the def getFile (basedir): global filelists for parent,dirnames in the folder Filenames in os.walk (basedir): for filename in filenames: ext = filename.split ('.') [- 1] # Statistics only the specified file type Skip some log and cache files if ext in whitelist: filelists.append (os.path.join (parent,filename)) # count the number of lines def countLine (fname): count = 0 # treat the file as binary, read. For file_line in open (fname, 'rb'). Readlines (): if file_line! =' 'and file_line! ='\ n': # filter out the empty line count + = 1 print (fname +'- -' Count) return countif _ _ name__ = ='_ main__': startTime = time.clock () getFile (basedir) totalline = 0 for filelist in filelists: totalline = totalline + countLine (filelist) print ('total lines:',totalline) print (' Done! Cost Time:% 0.2f second'% (time.clock ()-startTime)) 3. Scans the current directory and all subdirectories and displays the size. Import osimport sys try: directory = sys.argv [1] except IndexError: sys.exit ("Must provide an argument.") dir_size = 0 fsizedicr = {'Bytes': 1,' Kilobytes': float (1) / 1024, 'Megabytes': float (1) / (1024 * 1024),' Gigabytes': float (1) / (1024 * 1024 * 1024)} for (path, dirs) Files) in os.walk (directory): for file in files: filename = os.path.join (path, file) dir_size + = os.path.getsize (filename) fsizeList = [str (round (fsizedicr] * dir_size) 2) + "+ key for key in fsizedicr] if dir_size = 0: print (" File Empty ") else: for units in sorted (fsizeList) [::-1]: print (" Folder Size: "+ units) 4. Move all files longer than 240 days from the source directory to the destination directory. Import shutilimport sysimport timeimport osimport argparseusage = 'python move_files_over_x_days.py-src [SRC]-dst [DST]-days [DAYS]' description= 'Move files from src to dst if they are older than a certain number of days. Default is 240days'args_parser = argparse.ArgumentParser (usage=usage, description=description) args_parser.add_argument ('-src','- src', type=str, nargs='?', default='.', help=' (OPTIONAL) Directory where files will be moved from. Defaults to current directory') args_parser.add_argument ('- dst','--dst', type=str, nargs='?', required=True, help=' (REQUIRED) Directory where files will be moved to.') args_parser.add_argument ('- days','--days', type=int, nargs='?', default=240, help=' (OPTIONAL) Days value specifies the minimum age of files to be moved. Default is 240.') args = args_parser.parse_args () if args.days

< 0: args.days = 0src = args.src # 设置源目录dst = args.dst # 设置目标目录days = args.days # 设置天数now = time.time() # 获得当前时间if not os.path.exists(dst): os.mkdir(dst)for f in os.listdir(src): # 遍历源目录所有文件 if os.stat(f).st_mtime < now - days * 86400: # 判断是否超过240天 if os.path.isfile(f): # 检查是否是文件 shutil.move(f, dst) # 移动文件5.扫描脚本目录,并给出不同类型脚本的计数。import os import shutil from time import strftime logsdir="c:\logs\puttylogs" zipdir="c:\logs\puttylogs\zipped_logs" zip_program="zip.exe" for files in os.listdir(logsdir): if files.endswith(".log"): files1=files+"."+strftime("%Y-%m-%d")+".zip" os.chdir(logsdir) os.system(zip_program + " " + files1 +" "+ files) shutil.move(files1, zipdir) os.remove(files)6.下载Leetcode的算法题。import sysimport reimport osimport argparseimport requestsfrom lxml import html as lxml_htmltry: import htmlexcept ImportError: import HTMLParser html = HTMLParser.HTMLParser()try: import cPickle as pkexcept ImportError: import pickle as pkclass LeetcodeProblems(object): def get_problems_info(self): leetcode_url = 'https://leetcode.com/problemset/algorithms' res = requests.get(leetcode_url) if not res.ok: print('request error') sys.exit() cm = res.text cmt = cm.split('tbody>

') [- 2] indexs = re.findall (r' (\ d +)', cmt) problem_urls = ['https://leetcode.com' + url\ for url in re.findall (rang 12}: {}' .format (charEncoding.rjust (8),'('+ str (confidence*100) +'%)' FilePath)) if args.encoding and charEncoding! = 'Unknown' and confidence > 0. 6: # overwrite the source file outputPath = args.output + os.path.basename (filePath) if args.output else filePath with open (filePath,' ringing, encoding = charEncoding, errors = 'replace') as f: temp = f.read () with open (outputPath, 'wband, encoding = args.encoding) if the output directory is not set Errors = 'replace') as f: f.write (temp) so far I believe that you have a deeper understanding of "what are the practical scripts for Python", so you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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

Internet Technology

Wechat

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

12
Report