In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains what practical scripts Python has. The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn what practical scripts Python has.
1. Solve the problem of unzip garbled codes under linux.
Import os import sys import zipfile import argparse s ='\\ 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 (Arg v [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.'), path if _ _ name__ = ='_ main__': argv = sys.argv main (argv)
two。 Count the number of lines of code in the current root directory
# coding=utf-8 import os import time # set the root directory basedir ='. / 'filelists = [] # specify the file type you want to count whitelist = [' cpp', 'h'] # traverse the file, recursively traverse all def getFile (basedir): global filelists for parent,dirnames,filenames in os.walk (basedir): for filename in filenames: ext = filename.split ('.') [- 1] # only count 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 count if _ name__ = ='_ main__': startTime = time.clock () getFile (basedir) totalline = 0 for filelist in filelists: totalline = totalline + countLine (filelist) print ('totallin es:',totalline) print (' Done! Cost Time:% 0.2f second'% (time.clock ()-startTime))
3. Scans the current directory and all subdirectories and displays the size.
Import os import 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 shutil import sys import time import os import argparse usage= '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 = 0 src = 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 sys import re import os import argparse import requests from lxml import html as lxml_html try: import html except ImportError: import HTMLParser html = HTMLParser.HTMLParser() try: import cPickle as pk except ImportError: import pickle as pk class 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) {} Thank you for your reading The above is the content of "what practical scripts does Python have". After the study of this article, I believe you have a deeper understanding of what practical scripts Python has, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.