python - 将列表与文本文档进行比较

标签 python python-2.7

因此,我在代码中生成了一个列表,现在我想将其与现有文档进行检查,以了解在创建新文档之前存在哪些差异。

这是我的尝试:

  diff = ""
    if File2_Loc :
        File2 = open( File2_Loc , 'r' )
        for line in R_List :
            if line in File2 :
                pass
            else :
                diff += ( line.strip() + " not found in old file.\n" )
        for line in File2 :
            if line == "***** Differences founds : *****\n" :
                print( "Compared!")
                break
            if line in R_List :
                pass
            else :
                diff += ( line.strip() + " not found in new file.\n" )
    else :
        print( "No file inputted:" )
    for line in R_List :
        File1.write( line )
    File1.write( "***** Differences founds : *****\n" )
    if diff :
        File1.write( diff )
    else :
        File1.write( "None.\n" )

这里的问题是,R_List 中的每一行都没有在 File2 中找到,尽管 100% 应该是这样。

我已经在寻找解决方案,但我没有看到任何可以解决我的问题或对我的问题起作用的内容。

最佳答案

这是因为该文件仅被读取一次。如果您对其调用“in”,则不会再次迭代(它是从当前位置(即文件末尾)“读取”的)。因此,解决方案是使用 File2.readlines() 将所有文件读入内存,并尝试“进入”该内容:-)

    File2 = open( File2_Loc , 'r' )
    lines2 = File2.readlines()  # Define the lines here
    File2.close()               # This is also a good idea
    for line in R_List :
        if line in lines2 :     # Iterate over lines instead of file
            pass
        else :
            diff += ( line.strip() + " not found in old file.\n" )
    for line in lines2 :        # Iterate over lines instead of file
        if line == "***** Differences founds : *****\n" :
            print( "Compared!")
            break
        if line in R_List :
            pass
        else :
            diff += ( line.strip() + " not found in new file.\n" )

解决方案 2: 该解决方案使用集合和运算符“-”对它们进行析取:

    File2 = open( File2_Loc , 'r' )
    lines2 = File2.readlines()  # Define the lines here
    File2.close()               # This is also a good idea
    not_in_file2 = list(set(R_list) - set(lines2))
    not_in_rlist = list(set(lines2) - set(R_list))
    # Finish the diff output accordingly.

关于python - 将列表与文本文档进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18391618/

相关文章:

python - 使用已知列值更改 pandas DataFrame 多列中的值

python - 用于迁移学习的 Keras input_tensor 形状

python - Pyqt 超链接不启动外部应用程序

Python 跳过数字

Python 不显示类中打印语句的结果

python - Pillow - 如何使用阈值对图像进行二值化?

python - 系列的真值不明确 - 将系列月份名称转换为月份编号

python-2.7 - PySpark 使用统计信息写入 Parquet 二进制列(signed-min-max.enabled)

python - 将卡住集的元素写入 pandas 数据帧

python - python 中意外的关键字参数单击