2

所以我在我的代码中生成了一个列表,现在我想根据现有文档检查它,以查看在创建新文档之前有什么不同。

这是我的尝试:

  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% 应该是。

我已经在寻找解决方案,但我没有看到任何解决我的问题或解决我的问题的方法。

4

1 回答 1

2

这是因为该文件只被读取一次。如果你在它上面调用“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.
于 2013-08-22T22:28:42.487 回答