1
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.

2
  • 1
    Typically you want to append to the end rather than prepend to the start so you will have to manually do this yourself. Read the file into a list, re-open the file in "w" mode write the new first then write the rest. Commented Feb 20, 2024 at 13:59
  • 1
    Take a look at this answer to a similar problem also listed on SO Commented Feb 20, 2024 at 14:35

2 Answers 2

0

Like JonSG commented, a very straightforward approach is to:

  1. read the file into a list of rows
  2. insert/prepend the row you care about
  3. write the list out

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.)

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.