首页 > 解决方案 > 在 Python 中的已更改子目录中查找文件

问题描述

我有一个充满文件名的文本文件。喜欢:

C:\Folder\Subfolder_01\file_1001.csv
C:\Folder\Subfolder_02\file_3030.xls
...

我想检查文件是否仍然存在(这很容易)或者子文件夹的名称是否已更改。一些子文件夹的名称通过在其前面添加一些字符串来更改(以 4 位数字开头,例如C:\Folder\Subfolder_02\file_3030.xls已更改为C:\Folder\2019 - Subfolder_02\file_3030.xls)。

我试图用pathlib.glob(). 可以“手动”为一个特定文件执行此操作,例如

list(file.parent.parent.glob('* - Subfolder_02\file_3030.xls'))

它返回一个带有新文件名的列表。但我未能在围绕globwith 参数的循环中执行此操作。

这是我到目前为止所得到的,但是由于明显的原因,我尝试将 glob 与其他变量(使用 +)连接失败:

import pathlib

file = pathlib.Path(file_names.txt)
lines=[]

with open(file,'r') as f:
    # reading the txt-file line by line         
    for line in f:
        line = line.replace("\r", "").replace("\n", "")
        lines.append(line)

for file in lines:
    file = pathlib.Path(file)
    # check if file exists ...
    if file.exists():
        print('OK - ' + file.name)
    # ... if not, find new location
    else:
        new_files = list(file.parent.parent.glob('* - ') + file.name)
        print(files_files)  

标签: pythonpathlib

解决方案


如果您在原始位置找不到文件,我会将您的顶级目录设置为路径并使用它来全局目录下的文件。**在 glob 中使用将搜索所有文件夹。

# Set top level directory as desired.
parent_dir = Path('.')

# you can use splitlines() to parse the file into a list
with Path('file_names.txt').open() as f:
    files = f.read().splitlines()

for f in files:
    orig = Path(f)

    # Still in location, no need to look further
    if orig.exists():
        print(f"{orig.absolute()} is still in place.")
        continue

    # See if we can find it under parent_dir
    matches = [*parent_dir.glob(f"**/{orig.name}")]

    if len(matches) > 1:
        print("Multiple Matches Found")

    for match in matches:
        print(f"{orig.absolute()} might be in {match.absolute()}")

推荐阅读