-2

I want to write some data in a csv, but I have already written something in a few lines below so at the time of writing because obviously they are going to be written below (THE LIMIT) so to speak and I want them to be written above.

Here I put an image to give you an idea:

image

And here is the code that I am using:

            with open("priv/products.csv", 'a') as login:
                login.write("," + (introduce_product)) 
                login.write("," + (introduce_brand))
                login.write("," + "$" + (introduce_price))
                login.write("\n")
                login.close()
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
john eat
  • 3
  • 1
  • 3
  • 2
    When you open a file in `"a"` mode, it appends to the bottom of the file. What you need to do is to read in the existing file, modify the rows you get from the file, and write the modified rows into a new file. – Pranav Hosangadi Nov 09 '20 at 15:27

1 Answers1

1

Opening with a will append, you can try opening with w instead. Best is you can import it with pandas and write back to a CSV File:

import pandas as pd
df = pd.read_csv('priv/products.csv')
df[['product','brand','price']] = 'a'
df.to_csv('output.csv')
Wasif
  • 14,755
  • 3
  • 14
  • 34