Python实现批量文件修改后缀

decode_file()函数将指定路径文件配批量修改后缀名,然后存放到另一个指定位置;

recover_file()函数将修改过的文件名后缀批量还原;

import os

def decode_file():
    src_path = input(">>>Please input path need to decode:")
    tgt_path = input(">>>Please input path to release decode file:")
    L = []
    for root, dirs, files in os.walk(src_path):
        for file in files:
            L.append(os.path.join(root, file))
    for srcfile in L:
        tgtfile = tgt_path + srcfile[len(src_path) + 1:]
        tgtfile = tgtfile.split(".")[0] + "." + tgtfile.split(".")[-1] + "decode"
        try:
            src_f = open(srcfile, "rb")
        except IOError:
            print("###源文件打开错误,程序退出!!!")
            src_f.close()
            return
        if not os.path.exists(os.path.dirname(tgtfile)):
            os.makedirs(os.path.dirname(tgtfile))
        try:
            tgt_f = open(tgtfile, "wb")
        except IOError:
            print("###目标文件生产错误,程序退出!!!")
            tgt_f.close()
            return
        tgt_f.write(src_f.read())
        src_f.close()
        tgt_f.close()

def recover_file():
    src_path = input(">>>Please input path need to recover:")
    L = []
    for root, dirs, files in os.walk(src_path):
        for file in files:
            L.append(os.path.join(root, file))
    for srcfile in L:
        os.rename(srcfile,srcfile.split(".")[0] + "." + srcfile.split(".")[-1].replace("decode",""))

if __name__ == "__main__":
    while True:
        func = input("---------------------------------------\nMenu\nChoose a function:\n1.Decode file\n2.Recover file\n3.Exit\n---------------------------------------\n>>>")
        if func == "1":
            decode_file()
        elif func == "2":
            recover_file()
        elif func == "3":
            break
        else:
            print(">>>Error,choose again!\n")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值