我有名为“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))
关于python - 将文件名与文件夹名匹配,然后移动文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12930303/