使用python删除一个文件中存在于另一个文件中的行

时间:2017-03-14 08:50:36

标签: python

我很难删除使用python中的另一个文件行显示文件的行。我使用两个for循环进行字符串匹配,但它在循环的第二个循环中给出了重复的行。有没有其他方法可以做到这一点。感谢

Observable<Data> makeHttpCall(int param1, boolean param2);

Completable storeInDatabase(Data data);

Completable combinedCall(int param1, boolean param2);

3 个答案:

答案 0 :(得分:1)

您的变量名称令人困惑,因此我重命名了一对。我认为你需要打开一个新文件来编写结果(至少这会让你更清楚你要做的事情)。如果您想要相同的名称,可以在以后重命名该文件。

with open('results.csv','r+') as source:
    filter_lines = source.readlines()

with open('results_comments.csv','r') as f:
    lines = f.readlines()

with open('target.csv', 'w') as target:
    for line in lines:
        if line not in filter_lines:
            target.write(line)

答案 1 :(得分:1)

您可以尝试:

with open('results.csv','r') as source:
    lines_src = source.readlines()
with open('results_comments.csv','r') as f:
    lines_f = f.readlines()
destination = open("destination.csv","w")
for data in lines_src:
    if data not in lines_f:
        destination.write(data)
destination.close()

答案 2 :(得分:0)

with open('results.csv','r+') as source:
     lines = source.readlines()

f = open('results_comments.csv','r')
line = f.readlines()
line = filter(lambda x : x not in lines, line)
f.write('\n'.join(line))
f.close()