使用pathlib根据file.name

问题描述

目录 1 包含学生信息的子文件夹,每个子文件夹的命名规则如下

LASTNAME,FirsTNAME (STUDENTNUMBER)

目录 2 有 6 个子文件夹,其中包含 .xlsx生成绩表,这些 excel 文件中的每一个都使用以下约定命名

LASTNAME,FirsTNAME (STUDENTNUMBER) marking sheet.xlsx

我想使用 pathlib 获取目录 1 中子文件夹的名称,并在目录 2 中的子文件夹中找到匹配的评分表。

例如:

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

如果此问题不清楚,我们深表歉意,但我们将不胜感激。我也曾尝试从 this answer 中体现想法,但我对 Python 不够熟练,无法根据我的需要对其进行修改

解决方法

这是未经测试的,但我认为您想要做的是从目录 1 中的子文件夹创建潜在文件名,使用它在目录 2 中搜索,然后移动您找到的文件。

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)

我不确定您要将文件复制到何处,但您可以为 dest 的每个子文件夹或 dir1 的结果设置 rglob 变量。还有一点要注意,您可能会在不同的目录中找到多个具有目标名称的文件,因此我建议不要将它们全部复制到同一位置!