Python Forum
How to append a row from one csv file to another
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to append a row from one csv file to another
#1
Hi folks,

I need some direction on how to append a single row from one csv file to end of a list in another csv file.

The following is my code but I'm having trouble with copying only the second row to exclude the header plus it is appending with a skipped row.

with open('Preliminary.csv', 'r') as f1:
original = f1.read()

with open('Primary.csv', 'a') as f2:
f2.write('\n')
f2.write(original)

The problem with it is it's copying and appending the entire file and also placing it a few lines below the last in the destination csv file. I have a header that I want to avoid from copying over and only one row after which is the row that I need to append to the other csv file.

Thanks for any input you may provide.
Reply
#2
If you want to add to the end of the original file, you will need to open it in append mode
then simply write the new row to original file.
to open file for appending, mode is a+
so something like:
with open('Preliminary.csv', 'r') as f1, open('Primary.csv', 'a+') as f2:
    f2.write(f1.read())
I didn't try this, so backup before trying (always good policy at any rate)
Reply
#3
Thanks, Larz60. It appended but had several rows before and it copied the header from the file to the original file. Is there a way to have the header not append and also to eliminate the addition rows between the original file header and the appended rows?

Thanks again!
AJ
Reply
#4
Does anyone know how to copy a single row in a csv file and append to another csv file?
Reply
#5
read row by row:
with open('file', 'r') as fp:
   for line in file:
       line = line.strip()
Reply
#6
When you use f1.read() it reads the entire file, so you get header, all the stuff in one variable. If instead you use f1.readline() it reads a single line. You can then discard the first line, then loop reading the next lines and writing them to the second file. Test if you are at the end by testing for "" as the value from readline(). So, to not include the first line but copy all other lines something like

with open("foo.csv", r) as f1, open("bar.csv", a) as f2 :
    line = f1.readline() #remove header
    line = f1.readline()
    while line != "" :
        f2.write(line)
        line = f1.readline()
Reply
#7
Thanks for your help and sorry for the delayed reply!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020