需求:为了写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()
#批处理 修改所有的文件后缀名 支持子(子*)目录
这里贴参考了别人的博客:(也是我觉得写的很好的)
还陆陆续续的参考了很多正则表达式,字符串控制,绝对路径相对路径的用法
真的:人要不是懒 也不至于搞出这么多便捷的东西。
人生苦短 我用python