比较python中的两个文件并在新fi中保存行差异

2024-05-13 23:51:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个文本文件,它们的数据类似下面的例子。 使用python,我想将第一行中没有出现在第二个文件中的行保存到一个新文件中。这些行不包括在文件中。在

————第一个文件——第二个文件

   1   116969        116969
   2   116973        116977
   3   116977        117000
   4   117000        117028
   5   117004        117032
   6   117028        117036
   7   117032        117066
   8   117036        117104
   9   117062
   10  117066
   11  117097
   12  117104

新文件必须具有此结构。在

^{pr2}$

编辑:这是我目前为止的代码。列表sendfiles包含具有原始数据的文件的路径。列表receivefiles包含数据较少的文件的路径。在

    for x in range(0, len(sendfiles)):      
       f1 = open(sendfiles[x], 'r').readlines()
       f2 = open(receivefiles[x], 'r').readlines()
       path = sendfiles[x].strip('send.txt')
       final_file = path + 'out.txt'
       with open(final_file,'w') as f:
           ...

在unix中,我使用diff-f命令,但我知道必须编写一些python代码才能做到这一点。在

Edit2:这是send.txt的示例,这是receive.txt的示例


Tags: 文件数据path代码路径txtsend示例
1条回答
网友
1楼 · 发布于 2024-05-13 23:51:07
f1 = open('a', 'r').readlines()
f2 = open('b', 'r').readlines()
out = []
count = 1 
for i in f1:
    flag = False
    for j in f2:
        if i == j:
            flag = True
    if not flag:
        out.append(count)
    count+=1
for o in out:
    print o

优化的一个

^{pr2}$

相关问题 更多 >