from csv import *
items = ["Lenovo",1500,"Laptop"]
#using writer
with open("items.csv","a") as writable:
written = writer(writable)
written.writerow(items)
writable.close()
I had done this so far but this adds to the last row.
from csv import *
items = ["Lenovo",1500,"Laptop"]
#using writer
with open("items.csv","a") as writable:
written = writer(writable)
written.writerow(items)
writable.close()
I had done this so far but this adds to the last row.
Like JonSG commented, a very straightforward approach is to:
With Python's csv module and the basic reader and writer, that looks something like the following:
import csv
new_row = ["Lenovo", 1500, "Laptop"]
with open("input.csv", newline="") as f:
reader = csv.reader(f)
data = list(reader)
data.insert(1, new_row)
with open("output.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(data)
If I start with:
| Col1 | Col2 | Col3 |
|------|------|------|
| r1c1 | r1c2 | r1c3 |
| r2c1 | r2c2 | r2c3 |
| r3c1 | r3c2 | r3c3 |
I end up with:
| Col1 | Col2 | Col3 |
|--------|------|--------|
| Lenovo | 1500 | Laptop |
| r1c1 | r1c2 | r1c3 |
| r2c1 | r2c2 | r2c3 |
| r3c1 | r3c2 | r3c3 |
My sample CSV has a header, index 0, so I inserted the new row at index 1 (the first "row of data").
(I always recommend writing to a new file, making sure you like the result, then move/rename it to the original once your satisfied... at least when you're getting started.)
The straightforward way to add a line to the beginning of a file is to simply read the whole file, rewind, write the line, then re-write the data. No need for csv parsing at all and will likely be faster.
with open('items.csv', 'r+') as file:
data = file.read()
file.seek(0)
file.write('Lenovo,1500,Laptop\n')
file.write(data)