Python Forum

Full Version: Appending some rows in a .csv file from another .csv file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I need to append some of the rows in a .csv file from another file. I have never did it before, I found some snippets online to do that.
I thought I should do it line by line.
First, I wanted to find lines for appending in a File1, then find the same in a File2 and use the last element of File2 to append to the specified lines in file1.
I stuck Confused on the “find lines in File1/2. I need to match:
row[0] and row[1] File1 to :
row[0] and row[1] File2

Rows in File1 look like this:
match1, match2,something else,

Rows in File2 looking like this:
match1,match2,need this part for appending to File1,

from csv import writer
from csv import reader
match1 = 'ABBV50001'
match2 = 'CELL'

with open('C:/scripts/CSV/1.csv', 'r') as read_f1, \
        open('C:/scripts/CSV/2Ping.csv', 'r') as read_f2 :

    csv_reader1 = reader(read_f1)
    csv_reader2 = reader(read_f2)


    for row in csv_reader1 :
        if row[0] == match1 and row[1] == match2 :
            print (row)
        
        for row in csv_reader1 :
            if row[0] == match1 and row[1] == match2 :
                print (row)
OK. I could not make csv models to work Wall and I decided to go the long way.
I wanted to open both files, find matching lines and append the last element of one file to the end of the second file.
For some reason, the code stops after the first match Confused .
Here is a code:
import os
import re


hnd_stat = 'C:/Scripts/file1.txt'
cur_stat = 'C:/Scripts/file2.txt'


with open (cur_stat,'r+') as cur, open (hnd_stat, 'r') as hnd:
        
    for cln in cur :
        match_cnl = re.findall(r"^[A-Z]{4}\d{5},CELL", cln)

        if match_cnl :
            cln_sp = cln.split(",")
            cln_m  = cln_sp[0]+","+cln_sp[1]

            for hln in hnd :
                hln_sp = hln.split(",")
                hln_m = hln_sp[0]+","+hln_sp[1]
                    
                if hln_m in  cln :
                    print ("Appending ",cln+","+hln_sp[2])
Could anybody point me how to get around it?