Home > Net >  writing in open row in CSV file
writing in open row in CSV file

Time:10-26

i am trying to make a python code that takes first name, last name, and major, and puts them into a csv file. right now i am having trouble because this code just overwrites whatever is in the first row. How do i make it find the last row and write in that one?

`import csv

read_write = input("ENTER 0 FOR WRITE OR 1 FOR READ: ")
print(read_write)

if (read_write < '1'): # write CSV
    outfile = open("group_info.csv", 'w', newline="")
    Fname = input("ENTER FIRST NAME: ")
    Lname = input("ENTER LAST NAME: ")
    Major = input("ENTER MAJOR: ")
    info = "{},{},{}\n".format(Fname, Lname, Major)
    outfile.write(info)
outfile.close()`

CodePudding user response:

Try changing

outfile = open("group_info.csv", 'w', newline="")

to

outfile = open("group_info.csv", 'a', newline="")

and see if that helps you :) Not sure why you specify newline="", but you probably have a good reason to do that - I wouldn't.

CodePudding user response:

Currently you are opening file in write mode which erases the previous data. You need to open it in append mode which will open the previous file and append the new data in the end. Change your code from

    outfile = open("group_info.csv", 'w', newline="")

to

    outfile = open("group_info.csv", 'a', newline="")

CodePudding user response:

If you want to append new data to the end of the file, you need to change your code at line 7 like this:

outfile = open("group_info.csv", 'a', newline="")

It will open the file in 'appending mode', which will open the file for writing, appending to the end of the file if it exists.

And why does your code overwrites whatever is in the first row?

Because when we open a file, there is a cursor point to the data of the file. Your read or write operation will follow the cursor. And the cursor is pointing to the first position if you open a file in 'w mode', so your next write operation overwrites the first row of your data. When we open the file in 'appending mode', the cursor will point to the next to last position of the file, so your next write operation will append to the end of the file.

You can read the Python documentation about open if you need to know the details.

  • Related