Using Dict reader, how do I insert into CSV file?










0















I'm supposed to load a CSV file into the program memory, and when the user chooses option 1, they are allowed to add in a student's details. Upon pressing 'ENTER', the program will then write the user input into the csv file. I sort of got it to work, but if the user decides to add another user, it overides the first student details that's already in the CSV.



What I have so far is:



def insert_student():
print()
print("Insert a new student:")
first_name = input("Enter first name:")
last_name = input("Enter last name:")
student_id = input("Enter student ID:")

student_info = "first_name":first_name,"last_name":last_name,"student_id":student_id

import csv
filePath = "data.csv"
with open(filePath, 'w', newline='') as csvfile:
fieldnames = ['first_name', 'last_name', 'student_id']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow('first_name': first_name,
'last_name': last_name,
'student_id': student_id)
print("New Student Record Inserted")


How do I make it such that when the user decides to add multiple student details, it doesn't override it, and adds it to a new row?










share|improve this question






















  • You need to open your file in append mode if you want to modify it more than once.

    – toti08
    Nov 13 '18 at 14:17















0















I'm supposed to load a CSV file into the program memory, and when the user chooses option 1, they are allowed to add in a student's details. Upon pressing 'ENTER', the program will then write the user input into the csv file. I sort of got it to work, but if the user decides to add another user, it overides the first student details that's already in the CSV.



What I have so far is:



def insert_student():
print()
print("Insert a new student:")
first_name = input("Enter first name:")
last_name = input("Enter last name:")
student_id = input("Enter student ID:")

student_info = "first_name":first_name,"last_name":last_name,"student_id":student_id

import csv
filePath = "data.csv"
with open(filePath, 'w', newline='') as csvfile:
fieldnames = ['first_name', 'last_name', 'student_id']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow('first_name': first_name,
'last_name': last_name,
'student_id': student_id)
print("New Student Record Inserted")


How do I make it such that when the user decides to add multiple student details, it doesn't override it, and adds it to a new row?










share|improve this question






















  • You need to open your file in append mode if you want to modify it more than once.

    – toti08
    Nov 13 '18 at 14:17













0












0








0








I'm supposed to load a CSV file into the program memory, and when the user chooses option 1, they are allowed to add in a student's details. Upon pressing 'ENTER', the program will then write the user input into the csv file. I sort of got it to work, but if the user decides to add another user, it overides the first student details that's already in the CSV.



What I have so far is:



def insert_student():
print()
print("Insert a new student:")
first_name = input("Enter first name:")
last_name = input("Enter last name:")
student_id = input("Enter student ID:")

student_info = "first_name":first_name,"last_name":last_name,"student_id":student_id

import csv
filePath = "data.csv"
with open(filePath, 'w', newline='') as csvfile:
fieldnames = ['first_name', 'last_name', 'student_id']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow('first_name': first_name,
'last_name': last_name,
'student_id': student_id)
print("New Student Record Inserted")


How do I make it such that when the user decides to add multiple student details, it doesn't override it, and adds it to a new row?










share|improve this question














I'm supposed to load a CSV file into the program memory, and when the user chooses option 1, they are allowed to add in a student's details. Upon pressing 'ENTER', the program will then write the user input into the csv file. I sort of got it to work, but if the user decides to add another user, it overides the first student details that's already in the CSV.



What I have so far is:



def insert_student():
print()
print("Insert a new student:")
first_name = input("Enter first name:")
last_name = input("Enter last name:")
student_id = input("Enter student ID:")

student_info = "first_name":first_name,"last_name":last_name,"student_id":student_id

import csv
filePath = "data.csv"
with open(filePath, 'w', newline='') as csvfile:
fieldnames = ['first_name', 'last_name', 'student_id']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow('first_name': first_name,
'last_name': last_name,
'student_id': student_id)
print("New Student Record Inserted")


How do I make it such that when the user decides to add multiple student details, it doesn't override it, and adds it to a new row?







python






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 13 '18 at 14:12









AzaqiAzaqi

518




518












  • You need to open your file in append mode if you want to modify it more than once.

    – toti08
    Nov 13 '18 at 14:17

















  • You need to open your file in append mode if you want to modify it more than once.

    – toti08
    Nov 13 '18 at 14:17
















You need to open your file in append mode if you want to modify it more than once.

– toti08
Nov 13 '18 at 14:17





You need to open your file in append mode if you want to modify it more than once.

– toti08
Nov 13 '18 at 14:17












2 Answers
2






active

oldest

votes


















0














you have to open file with 'a' mode and write header only when it's new csv file,
try this:



import os
import csv

def insert_student():
print()
print("Insert a new student:")
first_name = input("Enter first name:")
last_name = input("Enter last name:")
student_id = input("Enter student ID:")

student_info = "first_name": first_name, "last_name": last_name, "student_id": student_id


filePath = "data.csv"


edit_mode = os.path.isfile(filePath)

with open(filePath, 'a', newline='') as csvfile:
fieldnames = ['first_name', 'last_name', 'student_id']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if not edit_mode:
writer.writeheader()
writer.writerow('first_name': first_name,
'last_name': last_name,
'student_id': student_id)

print("New Student Record Inserted")





share|improve this answer























  • It sort of works! But it didn't write the header. Any idea how to make it such that on the first entry, it writes the header, and on the subsequent entries, it doesn't? I tried checking if file size is = 0, and it doesn't work, because even when the file is empty, it's 1KB.

    – Azaqi
    Nov 13 '18 at 15:09


















0














Open the file in 'a' mode:



filePath = "data.csv" 
with open(filePath, 'a', newline='') as csvfile:
fieldnames = ['first_name', 'last_name', 'student_id']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow('first_name': first_name,
'last_name': last_name,
'student_id': student_id)
print("New Student Record Inserted")





share|improve this answer

























  • It sort of works, but it keeps writing the header everytime there is a new entry. Any workaround?

    – Azaqi
    Nov 13 '18 at 14:24











  • Yeah take the fieldnames out of the loop. See edited answer. What you could do is write a small function to initiate the file and only write the headers when starting the script. There isn't really a better way, as in, all other ways are way more complicated.

    – Imre_G
    Nov 13 '18 at 14:29












  • Sorry if I keep asking, but I didn't want to completely remove the header haha. What I meant was, for the first entry, it prints out the header, and subsequent entries, it just fills in without the header.

    – Azaqi
    Nov 13 '18 at 14:41











  • You roughly have three options. 1) Open the file before you write to see if there are headers there. Then write headers if they are not there yet. This is terrible for performance, but hey, it works. 2) Write a file init function which you call once when the script starts. A bit hacky, but depending on your level of seriousness might be the easiest option. 3) Define an object and make the insert_student method a method of that object. Then you can keep a variable "headers_added" or something similar in object state. If you are serious, this is the best option. Your call.

    – Imre_G
    Nov 13 '18 at 18:00











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53282939%2fusing-dict-reader-how-do-i-insert-into-csv-file%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














you have to open file with 'a' mode and write header only when it's new csv file,
try this:



import os
import csv

def insert_student():
print()
print("Insert a new student:")
first_name = input("Enter first name:")
last_name = input("Enter last name:")
student_id = input("Enter student ID:")

student_info = "first_name": first_name, "last_name": last_name, "student_id": student_id


filePath = "data.csv"


edit_mode = os.path.isfile(filePath)

with open(filePath, 'a', newline='') as csvfile:
fieldnames = ['first_name', 'last_name', 'student_id']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if not edit_mode:
writer.writeheader()
writer.writerow('first_name': first_name,
'last_name': last_name,
'student_id': student_id)

print("New Student Record Inserted")





share|improve this answer























  • It sort of works! But it didn't write the header. Any idea how to make it such that on the first entry, it writes the header, and on the subsequent entries, it doesn't? I tried checking if file size is = 0, and it doesn't work, because even when the file is empty, it's 1KB.

    – Azaqi
    Nov 13 '18 at 15:09















0














you have to open file with 'a' mode and write header only when it's new csv file,
try this:



import os
import csv

def insert_student():
print()
print("Insert a new student:")
first_name = input("Enter first name:")
last_name = input("Enter last name:")
student_id = input("Enter student ID:")

student_info = "first_name": first_name, "last_name": last_name, "student_id": student_id


filePath = "data.csv"


edit_mode = os.path.isfile(filePath)

with open(filePath, 'a', newline='') as csvfile:
fieldnames = ['first_name', 'last_name', 'student_id']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if not edit_mode:
writer.writeheader()
writer.writerow('first_name': first_name,
'last_name': last_name,
'student_id': student_id)

print("New Student Record Inserted")





share|improve this answer























  • It sort of works! But it didn't write the header. Any idea how to make it such that on the first entry, it writes the header, and on the subsequent entries, it doesn't? I tried checking if file size is = 0, and it doesn't work, because even when the file is empty, it's 1KB.

    – Azaqi
    Nov 13 '18 at 15:09













0












0








0







you have to open file with 'a' mode and write header only when it's new csv file,
try this:



import os
import csv

def insert_student():
print()
print("Insert a new student:")
first_name = input("Enter first name:")
last_name = input("Enter last name:")
student_id = input("Enter student ID:")

student_info = "first_name": first_name, "last_name": last_name, "student_id": student_id


filePath = "data.csv"


edit_mode = os.path.isfile(filePath)

with open(filePath, 'a', newline='') as csvfile:
fieldnames = ['first_name', 'last_name', 'student_id']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if not edit_mode:
writer.writeheader()
writer.writerow('first_name': first_name,
'last_name': last_name,
'student_id': student_id)

print("New Student Record Inserted")





share|improve this answer













you have to open file with 'a' mode and write header only when it's new csv file,
try this:



import os
import csv

def insert_student():
print()
print("Insert a new student:")
first_name = input("Enter first name:")
last_name = input("Enter last name:")
student_id = input("Enter student ID:")

student_info = "first_name": first_name, "last_name": last_name, "student_id": student_id


filePath = "data.csv"


edit_mode = os.path.isfile(filePath)

with open(filePath, 'a', newline='') as csvfile:
fieldnames = ['first_name', 'last_name', 'student_id']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if not edit_mode:
writer.writeheader()
writer.writerow('first_name': first_name,
'last_name': last_name,
'student_id': student_id)

print("New Student Record Inserted")






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 13 '18 at 14:27









Sagi GolanSagi Golan

413




413












  • It sort of works! But it didn't write the header. Any idea how to make it such that on the first entry, it writes the header, and on the subsequent entries, it doesn't? I tried checking if file size is = 0, and it doesn't work, because even when the file is empty, it's 1KB.

    – Azaqi
    Nov 13 '18 at 15:09

















  • It sort of works! But it didn't write the header. Any idea how to make it such that on the first entry, it writes the header, and on the subsequent entries, it doesn't? I tried checking if file size is = 0, and it doesn't work, because even when the file is empty, it's 1KB.

    – Azaqi
    Nov 13 '18 at 15:09
















It sort of works! But it didn't write the header. Any idea how to make it such that on the first entry, it writes the header, and on the subsequent entries, it doesn't? I tried checking if file size is = 0, and it doesn't work, because even when the file is empty, it's 1KB.

– Azaqi
Nov 13 '18 at 15:09





It sort of works! But it didn't write the header. Any idea how to make it such that on the first entry, it writes the header, and on the subsequent entries, it doesn't? I tried checking if file size is = 0, and it doesn't work, because even when the file is empty, it's 1KB.

– Azaqi
Nov 13 '18 at 15:09













0














Open the file in 'a' mode:



filePath = "data.csv" 
with open(filePath, 'a', newline='') as csvfile:
fieldnames = ['first_name', 'last_name', 'student_id']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow('first_name': first_name,
'last_name': last_name,
'student_id': student_id)
print("New Student Record Inserted")





share|improve this answer

























  • It sort of works, but it keeps writing the header everytime there is a new entry. Any workaround?

    – Azaqi
    Nov 13 '18 at 14:24











  • Yeah take the fieldnames out of the loop. See edited answer. What you could do is write a small function to initiate the file and only write the headers when starting the script. There isn't really a better way, as in, all other ways are way more complicated.

    – Imre_G
    Nov 13 '18 at 14:29












  • Sorry if I keep asking, but I didn't want to completely remove the header haha. What I meant was, for the first entry, it prints out the header, and subsequent entries, it just fills in without the header.

    – Azaqi
    Nov 13 '18 at 14:41











  • You roughly have three options. 1) Open the file before you write to see if there are headers there. Then write headers if they are not there yet. This is terrible for performance, but hey, it works. 2) Write a file init function which you call once when the script starts. A bit hacky, but depending on your level of seriousness might be the easiest option. 3) Define an object and make the insert_student method a method of that object. Then you can keep a variable "headers_added" or something similar in object state. If you are serious, this is the best option. Your call.

    – Imre_G
    Nov 13 '18 at 18:00
















0














Open the file in 'a' mode:



filePath = "data.csv" 
with open(filePath, 'a', newline='') as csvfile:
fieldnames = ['first_name', 'last_name', 'student_id']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow('first_name': first_name,
'last_name': last_name,
'student_id': student_id)
print("New Student Record Inserted")





share|improve this answer

























  • It sort of works, but it keeps writing the header everytime there is a new entry. Any workaround?

    – Azaqi
    Nov 13 '18 at 14:24











  • Yeah take the fieldnames out of the loop. See edited answer. What you could do is write a small function to initiate the file and only write the headers when starting the script. There isn't really a better way, as in, all other ways are way more complicated.

    – Imre_G
    Nov 13 '18 at 14:29












  • Sorry if I keep asking, but I didn't want to completely remove the header haha. What I meant was, for the first entry, it prints out the header, and subsequent entries, it just fills in without the header.

    – Azaqi
    Nov 13 '18 at 14:41











  • You roughly have three options. 1) Open the file before you write to see if there are headers there. Then write headers if they are not there yet. This is terrible for performance, but hey, it works. 2) Write a file init function which you call once when the script starts. A bit hacky, but depending on your level of seriousness might be the easiest option. 3) Define an object and make the insert_student method a method of that object. Then you can keep a variable "headers_added" or something similar in object state. If you are serious, this is the best option. Your call.

    – Imre_G
    Nov 13 '18 at 18:00














0












0








0







Open the file in 'a' mode:



filePath = "data.csv" 
with open(filePath, 'a', newline='') as csvfile:
fieldnames = ['first_name', 'last_name', 'student_id']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow('first_name': first_name,
'last_name': last_name,
'student_id': student_id)
print("New Student Record Inserted")





share|improve this answer















Open the file in 'a' mode:



filePath = "data.csv" 
with open(filePath, 'a', newline='') as csvfile:
fieldnames = ['first_name', 'last_name', 'student_id']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow('first_name': first_name,
'last_name': last_name,
'student_id': student_id)
print("New Student Record Inserted")






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 13 '18 at 14:31

























answered Nov 13 '18 at 14:19









Imre_GImre_G

912720




912720












  • It sort of works, but it keeps writing the header everytime there is a new entry. Any workaround?

    – Azaqi
    Nov 13 '18 at 14:24











  • Yeah take the fieldnames out of the loop. See edited answer. What you could do is write a small function to initiate the file and only write the headers when starting the script. There isn't really a better way, as in, all other ways are way more complicated.

    – Imre_G
    Nov 13 '18 at 14:29












  • Sorry if I keep asking, but I didn't want to completely remove the header haha. What I meant was, for the first entry, it prints out the header, and subsequent entries, it just fills in without the header.

    – Azaqi
    Nov 13 '18 at 14:41











  • You roughly have three options. 1) Open the file before you write to see if there are headers there. Then write headers if they are not there yet. This is terrible for performance, but hey, it works. 2) Write a file init function which you call once when the script starts. A bit hacky, but depending on your level of seriousness might be the easiest option. 3) Define an object and make the insert_student method a method of that object. Then you can keep a variable "headers_added" or something similar in object state. If you are serious, this is the best option. Your call.

    – Imre_G
    Nov 13 '18 at 18:00


















  • It sort of works, but it keeps writing the header everytime there is a new entry. Any workaround?

    – Azaqi
    Nov 13 '18 at 14:24











  • Yeah take the fieldnames out of the loop. See edited answer. What you could do is write a small function to initiate the file and only write the headers when starting the script. There isn't really a better way, as in, all other ways are way more complicated.

    – Imre_G
    Nov 13 '18 at 14:29












  • Sorry if I keep asking, but I didn't want to completely remove the header haha. What I meant was, for the first entry, it prints out the header, and subsequent entries, it just fills in without the header.

    – Azaqi
    Nov 13 '18 at 14:41











  • You roughly have three options. 1) Open the file before you write to see if there are headers there. Then write headers if they are not there yet. This is terrible for performance, but hey, it works. 2) Write a file init function which you call once when the script starts. A bit hacky, but depending on your level of seriousness might be the easiest option. 3) Define an object and make the insert_student method a method of that object. Then you can keep a variable "headers_added" or something similar in object state. If you are serious, this is the best option. Your call.

    – Imre_G
    Nov 13 '18 at 18:00

















It sort of works, but it keeps writing the header everytime there is a new entry. Any workaround?

– Azaqi
Nov 13 '18 at 14:24





It sort of works, but it keeps writing the header everytime there is a new entry. Any workaround?

– Azaqi
Nov 13 '18 at 14:24













Yeah take the fieldnames out of the loop. See edited answer. What you could do is write a small function to initiate the file and only write the headers when starting the script. There isn't really a better way, as in, all other ways are way more complicated.

– Imre_G
Nov 13 '18 at 14:29






Yeah take the fieldnames out of the loop. See edited answer. What you could do is write a small function to initiate the file and only write the headers when starting the script. There isn't really a better way, as in, all other ways are way more complicated.

– Imre_G
Nov 13 '18 at 14:29














Sorry if I keep asking, but I didn't want to completely remove the header haha. What I meant was, for the first entry, it prints out the header, and subsequent entries, it just fills in without the header.

– Azaqi
Nov 13 '18 at 14:41





Sorry if I keep asking, but I didn't want to completely remove the header haha. What I meant was, for the first entry, it prints out the header, and subsequent entries, it just fills in without the header.

– Azaqi
Nov 13 '18 at 14:41













You roughly have three options. 1) Open the file before you write to see if there are headers there. Then write headers if they are not there yet. This is terrible for performance, but hey, it works. 2) Write a file init function which you call once when the script starts. A bit hacky, but depending on your level of seriousness might be the easiest option. 3) Define an object and make the insert_student method a method of that object. Then you can keep a variable "headers_added" or something similar in object state. If you are serious, this is the best option. Your call.

– Imre_G
Nov 13 '18 at 18:00






You roughly have three options. 1) Open the file before you write to see if there are headers there. Then write headers if they are not there yet. This is terrible for performance, but hey, it works. 2) Write a file init function which you call once when the script starts. A bit hacky, but depending on your level of seriousness might be the easiest option. 3) Define an object and make the insert_student method a method of that object. Then you can keep a variable "headers_added" or something similar in object state. If you are serious, this is the best option. Your call.

– Imre_G
Nov 13 '18 at 18:00


















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53282939%2fusing-dict-reader-how-do-i-insert-into-csv-file%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

How to how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

Syphilis

Darth Vader #20