Search code examples
pythoncsvcomparison

How to compare CSV olumns from previous and next rows?


I am a beginner in Python and I am trying to check when two values in different rows are the same, and if they are the same, I want to add that value to the previous column in both rows. For instance, if this is my data:

'ola', 'b', '', '', 'c323'
'hello', 'i', '',  '', 'c324'
'hi', 'i', '', '', 'c324'

I would want it to return this:

'ola', 'b', '', '', 'c323'
'hello', 'i', '', 'c324', 'c324'
'hi', 'i', '', 'c324', 'c324'

I have tried a couple of things, e.g. this:

with open(filename, "r+") as file_one:
    reader_one = csv.reader(file_one, delimiter='\t') 
        with open(filename, "r+") as file_two:
            reader_two = csv.reader(file_two, delimiter='\t') 
                for row in reader_one:
                    corresp_info = row[3]
                    xml_info = row[4]
                    for compare_row in reader_two:
                        xml_compare = compare_row[4]
                        if xml_info == xml_compare:
                            corresp_info = xml_info
                        else:
                            continue

Solution

  • Here's how i see it :

    myCsv = open(filename, "r+").read().splitlines() #Opens the file and split it by lines
    newCsv = [myCsv[0].split(',')] #Adding first line to new CSV
    for i in range(1, len(myCsv)):  #looping through lines disregarding the first
         splitted = myCsv[i].split(',')  #split it by commas
         newCsv.append(splitted)  #append it
         for index, j in enumerate(splitted): #looping through comma separated values
               if j == newCsv[i-1][index]: #testing if equal to value of last row
                      newCsv[i-1][index-1] = newCsv[i-1][index] #changing values
                      newCsv[i][index-1] = newCsv[i][index]
    newCsv = map(lambda x: ','.join(x), newCsv) #remapping it into a csv like string
    open('newFile', 'w').write('\n'.join(newCsv)) #putting it into a new file
    

    Note that this is only an example on how i see it, so maybe it has typos or errors (even if i try to don't make some, but i'm not here to make code for you so i've not tested nor debugged). It's up to you to make your own code out of it