Python批处理修改文件后缀名

需求:为了写OJ自动挂题 在这样的情况下:

1.OJ挂题的需求要求所有的样例文件必须要以.in .out形式出现 (原本的数据形式是.txt)

2.并且要把所有的样例都压缩到一个压缩包里

3.既然支持一件处理文件 那么也要处理子目录下的文件

更新1:还要过滤掉input2(1).txt这样傻逼的形式

 

from selenium import webdriver
import json
import os
import re
import zipfile

def change(url):
    files = os.listdir(url)#列出当前目录下所有的文件
#    azip = zipfile.ZipFile('samples.zip', 'w')
    newname = ''
    flag = 0
    for file in files:
        portion = os.path.splitext(file)#分离文件名字和后缀
        if portion[1] == '':
            newPath = url + '\\' + portion[0]
            change(newPath)
        elif portion[1] ==".txt":
            flag = 1 #存在txt文件才压缩 
            if portion[0].startswith('input'):
                temp = str(portion[0])
                pos = temp.find('(')#过滤('(')
                if pos == -1:
                    pos = temp.find('(')#过滤('(')
                if pos >= 0:
                    temp = temp[0:pos]
                newname = str(re.sub("\D", "", temp))+".in"#更改后缀名
            elif portion[0].startswith('output'):
                temp = str(portion[0])
                pos = temp.find('(')
                if pos == -1:
                    pos = temp.find('(')
                if pos >= 0:
                    temp = temp[0:pos]
                newname = str(re.sub("\D", "", temp))+".out"
            os.chdir(url)
            os.rename(file, newname)
    if flag:#为了避免当前是一个文件夹 也要压缩
        condense(url)

def condense(url):
    azip = zipfile.ZipFile('samples.zip', 'w')
    for current_path, subfolders, filesname in os.walk(url):
        print(current_path, subfolders, filesname)
    for file in filesname:
        # 将当前路径与当前路径下的文件名组合,就是当前文件的绝对路径
        if file.endswith('in') or file.endswith('out'):
            azip.write(os.path.join('', file))
    azip.close()


def batchProcess():
    url = 'D:\safemon\Exercise\星际交流'
    change(url)

batchProcess()
#批处理 修改所有的文件后缀名 支持子(子*)目录

这里贴参考了别人的博客:(也是我觉得写的很好的)

1.Python超简单批量改文件后缀

2.Python操作Zip文件

还陆陆续续的参考了很多正则表达式,字符串控制,绝对路径相对路径的用法

真的:人要不是懒 也不至于搞出这么多便捷的东西。

人生苦短 我用python

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值