1

Directory 1 contains subfolders of student info, each subfolder is named with the following convention

LASTNAME, FIRSTNAME (STUDENTNUMBER)

Directory 2 has 6 subfolders that contain .xlsx student grade sheets in them, each of these excel files is named with the following convention

LASTNAME, FIRSTNAME (STUDENTNUMBER) marking sheet.xlsx

I'd like to use pathlib to take the names of the subfolders in directory 1 and find the matching grading sheet in the subfolders in directory 2.

For example:

import pathlib as pl

dir1 = pl.WindowsPath(r'C:\Users\username\directory_1')
dir2 = pl.WindowsPath(r'C:\Users\username\directory_2')

for (subfolder, file) in zip(dir1.iterdir(), dir2.rglob("*.xlsx")):
    if str.lower(subfolder.name) is in str.lower(file.name): #I run up against a wall here
        copy file into subfolder
        print(f'{file.name} copied to {subfolder.name}')

Apologies if this question is unclear but any assistance would be appreciated. I have also tried to impliment ideas from this answer but I'm not skilled enough with python to modify it for my needs.

KevOMalley743
  • 551
  • 3
  • 20

1 Answers1

2

This is untested, but I think what you want to be doing is creating the potential file name from the subfolders in directory 1, using that to search in directory 2 and then moving files that you find.

from pathlib import Path
from shutil import copy

dir1 = Path("C:\Users\username\directory_1")
dir2 = Path("C:\Users\username\directory_2")

for folder in dir1.iterdir():
    # We're only interested in folders
    if not folder.is_dir():
        continue

    target_file = f"{folder.name} marking sheet.xlsx"
    for file in dir2.rglob(target_file):
        # copy(file, dest)

I'm not sure about where you want the files to be copied to, but you can set the dest variable for each subfolder of dir1 or result of the rglob. Another thing to note, you may find multiple files with the target name in different directories so I would caution against copying them all to the same place!

Alex
  • 6,610
  • 3
  • 20
  • 38
  • Thank you very much, I see what you're doing here. ```dest``` is the folder in dir1. So I want to take the folder name in dir1 and use that to find a .xlsx file in dir2 and copy that file into the subfolder in dir1 that shares the name. I can play around with what you've written and post back. Thanks a million for your time @Alex – KevOMalley743 Jun 29 '21 at 18:11
  • 1
    Ah, yes, that's certainly do-able. If you want I can expand my answer with what I would do, but I don't want to stop you finding the answer yourself! Sometimes all it takes is pointing in the right direction – Alex Jun 29 '21 at 18:43
  • 1
    I'm on another task for a couple of hours but I'll post my version of this in a few hours, thanks again for the help. – KevOMalley743 Jun 30 '21 at 07:43