Fork me on GitHub

一 python文件创建

   

import os
import argparse

def file_write(file_name,msg):
    f = open(file_name,"a")
    f.write(msg)
    f.close




def get_parser():
    parser = argparse.ArgumentParser(description='create a file and write message in it')
    parser.add_argument('file_name', metavar='file_name', type=str, nargs=1,
                        help='file_name to write')
    parser.add_argument('file_message', metavar='message_name', type=str, nargs=1,
                        help='file_message to write')
    return parser

def main():
    parser = get_parser()
    args = vars(parser.parse_args())

    file_name = args['file_name'][0]
    file_message = args['file_message'][0]

    file_write(file_name,file_message)

if __name__=='__main__':
    main()

 

二 python 文件查找

 

import argparse
import os

def batch_search(work_dir,ext_file):

    for filename in os.listdir(work_dir):
        split_file = os.path.splitext(filename)
        root_name,file_ext = split_file

        if ext_file == filename:
            print("search file:",filename)

def get_parser():
    parser = argparse.ArgumentParser(description='search file on it')
    parser.add_argument('work_dir', metavar='WORK_DIR', type=str, nargs=1,
                        help='the directory where to change extension')
    parser.add_argument('new_ext', metavar='NEW_EXT', type=str, nargs=1, help='new extension')
    return parser

def main():
    parser = get_parser()
    args = vars(parser.parse_args())

    work_dir = args['work_dir'][0]
    new_ext = args['new_ext'][0]

    batch_search(work_dir,new_ext)

if __name__=='__main__':
    main()

 

三  python文件重命名

 

import argparse
import os

def batch_rename(work_dir,old_ext,new_ext):

    for filename in os.listdir(work_dir):
        split_file = os.path.splitext(filename)
        root_name,file_ext = split_file
        print(file_ext)

        if old_ext == filename:
            newfile = new_ext
            print(newfile)
            os.rename(
                os.path.join(work_dir,filename),
                os.path.join(work_dir,newfile)
            )

def get_parser():
    parser = argparse.ArgumentParser(description='change extension of files in a working directory')
    parser.add_argument('work_dir', metavar='WORK_DIR', type=str, nargs=1,
                        help='the directory where to change extension')
    parser.add_argument('old_ext', metavar='OLD_EXT', type=str, nargs=1, help='old extension')
    parser.add_argument('new_ext', metavar='NEW_EXT', type=str, nargs=1, help='new extension')
    return parser

def main():
    parser = get_parser()
    args = vars(parser.parse_args())

    work_dir = args['work_dir'][0]
    old_ext = args['old_ext'][0]
    new_ext = args['new_ext'][0]
    print(new_ext)

    batch_rename(work_dir,old_ext,new_ext)

 


四 总结

  

   作为一名程序猿,基本功要常练,武术上有个行话,练武不练功,到老一场空,基本功不能少啊。要多学习,多学习。有空就分析一下源码,写一写小软件,这个才是不会落伍啊。

     

 

posted on 2021-04-14 18:36  虚生  阅读(139)  评论(0编辑  收藏  举报