python 复制文件_Python实践(4):复制文件并替换关键字符

    平时添加新用例往往在原来用例的基础上改,由于仿真脚本的限制(要求用例文件名和其中的class名相同),此时需要替换新用例中的class名:大概的过程就是先cp文件,然后gvim打开,输入替换命令替换。     下面这个py脚本实现复制 文件 时,自动修改 class名的功能 :
# python copy_file.py TC_1 TC_2
"""file_name: copy_file.py"""import sysdef main():    if(len(sys.argv) != 4):        print("options not enough.")        sys.exit()    else:        o_file = sys.argv[1]        n_file = sys.argv[2]        suffix = sys.argv[3]        # key_words(o_file, n_file)        copy_file(o_file, n_file, suffix)def copy_file(old_file, new_file, suffix):    new_lines = []    try:        f_obj = open(old_file+"."+suffix)    except FileNotFoundError:        print(old_file+"."+suffix+" : no such file.")    else:        for line in f_obj:            if old_file in line:                new_lines.append(                    line.replace(old_file, new_file)                    )            else:                new_lines.append(line)        f_obj.close()        try:            # f_obj = open(new_file+"."+suffix)            f_obj = open(new_file+"."+suffix, "w")        except FileNotFoundError:            print(new_file+"."+suffix+" : no such file.")        else:            for line in new_lines:                f_obj.write(line)            f_obj.close()main()
    但是和老司机交流发现,实际上很少有人会向上面这样实现。为什么?下面2行的shell脚本能实现同样的功能!
# file_name: copy_file.shcp $1.sv $2.svsed -i "s/$1/$2/g" $2.sv

    有没有想起“铁锤人倾向”呢?

db7d24774517e0a4d03f20d51d8d94c0.png

参考资料:

1 Linux sed 命令,https://www.runoob.com/linux/linux-comm-sed.html

2 Shell 传递参数,https://www.runoob.com/linux/linux-shell-passing-arguments.html

3 cygwin下切换到其他磁盘, https://blog.csdn.net/lts_cxl/article/details/17248727

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值