将文件名与foldernames匹配,然后移动文件

时间:2012-10-17 08:38:06

标签: 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)

2 个答案:

答案 0 :(得分:6)

您不需要正则表达式。

这样的事情怎么样:

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))

答案 1 :(得分:0)

考虑到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))