【问题标题】:Python: find missing files from pairsPython:从对中查找丢失的文件
【发布时间】:2021-07-21 06:45:29
【问题描述】:

我正在尝试查找一些丢失的文件,但这些文件是成对的。

例如,我们有如下文件: 文件 1_LEFT file1_RIGHT 文件 2_LEFT file2_RIGHT 文件 3_LEFT file4_RIGHT ...

ideea 是名称相同但它们有左/右对。通常我们有数千个文件,但在某个地方,我们会发现一些文件没有一对。就像 file99_LEFT 存在但 RIGHT 缺失(反之亦然)。

我正在尝试在 python 2.7 中编写一个脚本(是的,我出于个人原因使用了旧的 python ......不幸的是)但我不知道如何实现。 尝试过的想法: - 逐个验证它们并检查我们在当前文件中是否有 RIGHT 并且在以前的文件中是否有 LEFT,打印确定,否则打印不匹配的文件。但是在打印第一个之后,由于结构发生了变化,所有其他都失败了,此时我们将不会有左右相邻的,它们的顺序将重新排列 - 为 LEFT 和 RIGHT 创建单独的列表并比较它们,但会再次找到第一个但对其他人不起作用。

到目前为止我使用的代码:

import os
import fnmatch,re



path = raw_input('Enter files path:')

for path, dirname, filenames in os.walk(path):
        for fis in filenames:
            print fis

        print len(filenames)
        for i in range(1,len(filenames),2):
            print filenames[i]
            if "RIGHT" in filenames[i] and "LEFT" in filenames[i-1]:
                print "Ok"
            else:
                print "file >"+fis+"< has no pair"
                f = open(r"D:\rec.txt", "a")
                f.writelines(fis + "\n")

f.close()

感谢您的宝贵时间!

【问题讨论】:

    标签: list python-2.7 file find


    【解决方案1】:

    我们可以使用glob 列出给定路径中的文件,并按搜索模式过滤。

    如果我们考虑一组所有 LEFT 文件名和另一组所有 RIGHT 文件名,我们可以说您正在寻找不在这两组交集中的元素吗?

    这就是这两组中的“symmetric difference”。

    import glob
    
    # Get a list of all _LEFT filenames (excluding the _LEFT part of the name)
    # Eg: ['file1', 'file2' ... ]. 
    # Ditto for the _RIGHT filenames
    # Note: glob.glob() will look in the current directory where this script is running. 
    left_list = [x.replace('_LEFT', '') for x in glob.glob('*_LEFT')]
    right_list = [x.replace('_RIGHT', '') for x in glob.glob('*_RIGHT')] 
    
    # Print the symmetric difference between the two lists
    symmetric_difference = list(set(left_list) ^ set(right_list))
    print symmetric_difference
    
    # If you'd like to save the names of missing pairs to file
    with open('rec.txt', 'w') as f:
        for pairname in symmetric_difference:
            print >> f, pairname
    
    # If you'd like to print which file (LEFT or RIGHT) is missing a pair
    for filename in symmetric_difference:
        if filename in left_list:
            print "file >" + filename + "_LEFT< has no pair"
        if filename in right_list:
            print "file >" + filename + "_RIGHT< has no pair"
    

    【讨论】:

      猜你喜欢
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-19
      • 2011-10-06
      • 1970-01-01
      • 2018-07-29
      相关资源
      最近更新 更多