小编给大家分享一下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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。