Python 将文件名与文件夹名匹配,然后移动文件
我有名为“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”等 我是这样开始的,但我被卡住了,因为我对常规表达式缺乏理解Python 将文件名与文件夹名匹配,然后移动文件,python,regex,Python,Regex,我有名为“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)
这不需要正则表达式 像这样的怎么样:
import glob
files = glob.glob('*.txt')
for file in files:
# this will remove the .txt extension and keep the "aN"
first_part = file[:-4]
# find the matching directory
dir = glob.glob('%s_*/' % first_part)[0]
os.rename(file, os.path.join(dir, file))
考虑到Inbar Rose的建议,这是一个轻微的选择
import os
import glob
files = glob.glob('*.txt')
dirs = glob.glob('*_*')
for file in files:
filename = os.path.splitext(file)[0]
matchdir = next(x for x in dirs if filename == x.rsplit('_')[0])
os.rename(file, os.path.join(matchdir, file))
这个解决方案对答案非常具体,并不是最好的解决方法。您应该使用
os.path.splitext()
来获取(文件名,扩展名)
对。@Inbar Rose,splitext()
是更通用的解决方案,以防您需要从文件名中删除扩展名。然而,我不确定这种情况是否会一直持续下去。OP未指定该目录。这假定文件和文件夹位于同一目录中。除此之外,它还假设所有文件夹都位于同一目录中。应该有一本字典,格式为{'a1':“folder/path/to/a1_1998”,“a2':“folder/path/to/a2_1999”}
。。。。从字符串中提取一个片段并不表示您实际在做什么,在本例中,OP明确表示希望文件名进入其文件夹。另外-os.rename
并不总是最适合使用的,imhoshutil.move
更好。感谢大家将Hans的答案与shutil.move结合起来移动文件,太棒了!!(如上所述)。我会投票,但很抱歉没有足够的两点代表Hanks Talvalin这应该可以做到,我只是在向我的文件添加路径时遇到了matchdir行的问题,如下所示:import os import glob files=glob.glob(r'C:\Wam*.docx')dirs=glob.glob(r'C:\Wam*\u*'))还有其他方法指定工作目录吗?使用双引号指定目录应该可以解决这个问题。例如:files=glob.glob(“C:\Wam*.docx”)