我有名为“a1.txt”,“a2.txt”,“a3.txt”,“a4.txt”,“a5.txt”等文件.然后我有名为“a1_1998”,“a2_1999”,“a3_2000”,“a4_2001”,“a5_2002”等文件夹.
我想在文件“a1.txt”和&之间进行连接.文件夹“a1_1998”例如. (我猜我需要经常表达才能做到这一点).然后使用shutil将文件“a1.txt”移动到文件夹“a1_1998”,将文件“a2.txt”移动到文件夹“a2_1999”等….
我已经开始这样了,但是我因为对常规表达缺乏了解而陷入困境.
import re
##list files and folders
r = re.compile('^a(?P')
m = r.match('a')
m.group('id')
##
##Move files to folders
我稍微修改了下面的答案,使用shutil来移动文件,做了诀窍!
import shutil
import os
import glob
files = glob.glob(r'C:\Wam\*.txt')
for file in files:
# this will remove the .txt extension and keep the "aN"
first_part = file[7:-4]
# find the matching directory
dir = glob.glob(r'C:\Wam\%s_*/' % first_part)[0]
shutil.move(file, dir)