【问题标题】:Checking if filename prefixes match parent directory prefix recursively with pathlib使用 pathlib 递归检查文件名前缀是否与父目录前缀匹配
【发布时间】:2023-01-19 00:33:00
【问题描述】:

我编写了一个脚本,该脚本使用 pathlib 将用户提供的文件列表与目标目录中的实际文件进行比较。然后它返回预期但未找到的文件列表,以及已找到但未预期的文件。它工作得很好。

我现在的问题是我想验证文件名前缀是否与其父目录的前缀匹配,如果不匹配则返回错误。因此,名为 abc2022_001 的文件夹应包含以 abc2022_ 而非 abc2023_ 开头的文件。这是我到目前为止所拥有的:

from pathlib import Path

fileList = open("fileList.txt", "r")
data = fileList.read()
fileList_reformatted = data.replace('\n', '').split(",")
print(fileList_reformatted)

p = Path('C:/Users/Common/Downloads/compare').rglob('*')
filePaths = [x for x in p if x.is_file()]
filePaths_string = [str(x) for x in filePaths]
print(filePaths_string)

differences1 = []
for element in fileList_reformatted:
    if element not in filePaths_string:
        differences1.append(element)

print("The following files from the provided list were not found:",differences1)

differences2 = []
for element in filePaths_string:
    if element not in fileList_reformatted:
        differences2.append(element)

print("The following unexpected files were found:",differences2)

wrong_location = []
for element in p:
    if element.Path.name.split("_")[0:1] != element.Path.parent.split("_")[0:1]:
        wrong_location.append(element)
    
print("Following files may be in the wrong location:",wrong_location)

该脚本运行,但在测试目录上未返回任何错误。我哪里错了?谢谢!

【问题讨论】:

    标签: python list pathlib


    【解决方案1】:

    您可以尝试只从该行的拆分中选择第一个元素。

    if element.Path.name.split("_")[0:1] != element.Path.parent.split("_")[0:1]:
    

    像这样

     if element.Path.name.split("_")[0] != element.Path.parent.split("_")[0]:
    

    第一个版本比较两个列表['abc22'] == ['abc23'],而不是实际值'abc22' == 'abc23'。这可能是原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 2015-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-16
      • 1970-01-01
      相关资源
      最近更新 更多