• 技术文章 >Python技术 >Python基础教程

    Python有哪些实用的脚本?

    2020-11-07 11:44:39原创1785
    学过编程的都知道,除了要写代码,测试也是很重要的环节。大家都只听说程序员小哥哥的头发是稀有的东西,那如果测试的速度变快岂不是可以早早下班?今天小编就为大家带来几个Python中几个实用的脚本。

    1.解决 linux 下 unzip 乱码的问题。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    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.统计当前根目录代码行数。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    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.扫描当前目录和所有子目录并显示大小。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    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天以上的所有文件移动到目标目录。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    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.扫描脚本目录,并给出不同类型脚本的计数。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    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个实用的脚本。更多Python学习推荐:PyThon学习网教学中心

    专题推荐:python脚本
    上一篇:如何用python玩跳一跳(ios版) 下一篇:Python的图形界面(GUI)是什么?怎么学?

    相关文章推荐

    • 执行python脚本出现乱码怎么解决• 为什么双击python脚本不能运行• linux怎么执行python脚本• sublime编译python脚本出错了怎么办• 关于Python脚本中执行adb命令的方法

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网