Skip to content Skip to sidebar Skip to footer

Match Filenames To Foldernames Then Move Files

I have files named 'a1.txt', 'a2.txt', 'a3.txt', 'a4.txt', 'a5.txt' and so on. Then I have folders named 'a1_1998', 'a2_1999', 'a3_2000', 'a4_2001', 'a5_2002' and so on. I would li

Solution 1:

You do not need regular expressions for this.

How about something like this:

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 directorydir = glob.glob('%s_*/' % first_part)[0]
    os.rename(file, os.path.join(dir, file))

Solution 2:

A slight alternative, taking into account Inbar Rose's suggestion.

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

Post a Comment for "Match Filenames To Foldernames Then Move Files"