我有名为“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)
也许增加一个测试,如果第2个'glob.glob()'真的正好返回一个目录名称... – glglgl
这种解决方案是非常具体的答案,而不是要做到这一点的最好办法。你应该使用'os.path.splitext()'来获得'(filename,extension)'对。 –
@Inbar Rose,'splitext()'是更常用的解决方案,以防您需要从文件名中删除扩展名。不过,我不确定这会永远如此。 OP没有具体说明。 –