Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (16.4k points)

Let's say I have two CSV files and In the third CSV file, I want to print the difference between those CSV files.

First CSV has an old list of hash

Second CSV has the new list of hash which will have both old and new hash.

This is my code:

import csv

t1 = open('old.csv', 'r')

t2 = open('new.csv', 'r')

fileone = t1.readlines()

filetwo = t2.readlines()

t1.close()

t2.close()

outFile = open('update.csv', 'w')

x = 0

for i in fileone:

    if i != filetwo[x]:

        outFile.write(filetwo[x])

    x += 1

outFile.close()

I don't want to use the diff

1 Answer

0 votes
by (26.4k points)

Since you are comparing each line in fileone to filetwo, that will become a problem. If in case, there's one extra line in one file, here the lines won't be equal again.

Try this code:

with open('old.csv', 'r') as t1, open('new.csv', 'r') as t2:

    fileone = t1.readlines()

    filetwo = t2.readlines()

with open('update.csv', 'w') as outFile:

    for line in filetwo:

        if line not in fileone:

            outFile.write(line)

Interested to learn more about Python? Come & join: python course course 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...