主要用到的知识点(python笔记中也有)
1. 文件移动:
import shutil
for file in os.listdir(path):
shutil.move(os.path.join(path, file), os.path.join(new_path, file))
# shutil函数第一个参数是旧的文件路径,第二个是新的文件的位置和新名称
2. 文件重命名:
os.rename(os.path.join(path, file), os.path.join(path, dic[file] + '.m4a'))
# 原理就是join函数把路劲和文件名称连接,
# rename函数第一个参数是旧的文件路径,第二个是新的文件的位置和新名称
3.正则表达式(部分): 找数字:data = re.findall('\d+', file) # 注意不能直接写成\d+,写成\d+才规范 找指定的特征:
data2 = re.findall(".*?<title>(.*?)_(.*?)_单曲在线试听_酷我音乐</title>", result3.text[0:250])
# rename函数第一个参数是需要正则匹配的.*? 第二个参数是对 哪个字符串 执行这样的查找操作
源码如下:
import os
import re
import shutil
path = r'D:\BaiduNetdiskDownload\CET6'
def new_name_func(zhenti): # 返回标准化的文件名称
first = name[0][0][-4:] # 从倒数第4个开始取,可能前面有其他杂质
if len(name[0][2]) == 3: # 部分套题的编号可能会是010之类的,所以取中间的
tao1 = '-' + name[0][2][1:-1]
else:
tao1 = '-' + name[0][2]
if len(name[0][1]) == 1: # 是6月份的那么就加个0,变成06跟12对称
new_name2 = first + '0' + name[0][1] + tao1 + zhenti
else:
new_name2 = first + name[0][1] + tao1 + zhenti
return new_name2
def my_move_to_floder(path):
path_to_make = r'D:\BaiduNetdiskDownload\New_CET6' # 创建新文件夹的地址,把所有新的CET6文件存到该目录
if not os.path.exists(path_to_make):
os.mkdir(path_to_make)
for i in os.listdir(path): # 新目录下的CET6文件夹创建年份,在创建”卷子“,和“听力”,
path_to_make = r'D:\BaiduNetdiskDownload\New_CET6' + '\\' + i[:4]
if not os.path.exists(path_to_make):
os.mkdir(path_to_make)
path = r'D:\BaiduNetdiskDownload\CET6' + '\\' + i
for j in os.listdir(path):
if '01' in j or '03' in j or '04' in j: # j是文件夹(真题、解析、听力),这里文件夹名称有规律,01就是真题,03是解析,04是听力文件夹
if '01' in j or '03' in j:
if not os.path.exists(path_to_make + '\\' + '卷子'):
os.mkdir(path_to_make + '\\' + '卷子')
if '04' in j:
if not os.path.exists(path_to_make + '\\' + '听力'):
os.mkdir(path_to_make + '\\' + '听力')
path = r'D:\BaiduNetdiskDownload\CET6' + '\\' + i + '\\' + j # 这里就是移动文件了
for all in os.listdir(path): # all是pdf等文件,判断。split后是否合适
if all.split('.')[-1] == 'pdf':
shutil.move(os.path.join(path_to_make, all), os.path.join(path_to_make + '\\' + '卷子', all))
if all.split('.')[-1] == 'mp3' or all.split('.')[-1] == 'MP3':
shutil.move(os.path.join(path_to_make, all), os.path.join(path_to_make + '\\' + '听力', all))
if __name__ == '__main__':
my_move_to_floder(path)
for i in os.listdir(path):
for j in os.listdir(path + i):
if '01' in j or '03' in j or '04' in j:
for p in os.listdir(path + i + "\\" + j): # 取出每个文件名称的循环
name = re.findall('(.*?)年(.*?)月.*?((.*?)).*?', p)
if '.mp3' in p:
can_shu = '听力'
elif '.lrc' in p:
continue # 不管lrc文件,听力的没分秒说了啥话
else:
if '真题' in p:
can_shu = '真题'
if '解析' in p:
can_shu = '解析'
my_new_name = new_name_func(can_shu) + "." + p.split('.')[-1]
print(my_new_name)
os.rename(os.path.join(path + i + "\\" + j, p), os.path.join(path + i + "\\" + j, my_new_name))