0

I have not managed to achieve it. but what confuses me the most is how to add an element in a line "n" of my csv, for example I want to add a line in the line 2 of my csv.

mycsv.csv

name,last name
yeison, smith
lola, boa
elmo, spitia
anderson, exneider
juan, ortega

this is my code:

with open('mycsv.csv', 'w') as f:
 #I need add "barney, cubides" on position [2] of my csv
 f.write("barney, cubides") #not works properly..

how can do it?

yavg
  • 2,761
  • 7
  • 45
  • 115
  • 1
    Possible duplicate of [Insert line at middle of file with Python?](https://stackoverflow.com/questions/10507230/insert-line-at-middle-of-file-with-python) – fabianegli Mar 20 '19 at 04:01

1 Answers1

0

You have to write to file after you read it. So read the whole csv and save each line as a list, insert your new line where you want to, and then re-write the whole file.

index_to_insert = 2
new_csv = []
new_line = "barney, cubides\n"
with open("mycsv.csv", "r") as f:
    new_csv = f.readlines()
new_csv.insert(index_to_insert, new_line)
with open("mycsv.csv", "w") as f:
    for line in new_csv:
        f.write(line)

ps. You might want to get rid of the whitespaces before and after the commas in your csv file.

Ignatius
  • 2,745
  • 2
  • 20
  • 32