我有名为“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))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)