您好,登錄后才能下訂單哦!
小編給大家分享一下Python中5個實用的腳本代碼,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
1.解決 linux 下 unzip 亂碼的問題。
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='解決unzip亂碼') p.add_argument('xxx', type=str, nargs='*', \ help='命令對象.') p.add_argument('-s', '--secret', action='store', \ default=None, help='密碼') 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.統計當前根目錄代碼行數。
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[key] * 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)
3.掃描當前目錄和所有子目錄并顯示大小。
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[key] * 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.將源目錄240天以上的所有文件移動到目標目錄。
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 240 days' 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)
以上是Python中5個實用的腳本代碼的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。