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 - 从另一个类借用类方法(Python 3)

Python 字典带有作为参数传递的数组值?

python - 如何修复 Anaconda 找不到的 : pyconfig. h

python多处理卡住

python-2.7 - 在类的一个函数中获取用户输入并在 Python 中的另一个函数中使用它

python - 如果存在打印语句,Pycharm 会无限期地挂起单元测试

python - send_message() 缺少 1 个必需的位置参数 : 'message'

python - reportlab 表格中段落的行间距和拟合

Python - Tkinter 标签输出?

python - python 中的 import gv 是什么?