简体   繁体   中英

Writing to a CSV file using Python and adding data

I have a python script that tell me what 'period' it is (for school) which then outputs into a csv file:

import datetime
import csv

format = "%H%M"
today = datetime.datetime.today()
s = today.strftime(format)
period = 0

ofile = open('Period.csv', "wb")
writer = csv.writer(ofile, delimiter=',')

if s > "0845" < "0945":
 period = 1
if s >= "0945" < "1120":
 period = 2
if s >= "1120" < "1220":
 period = 3
if s >= "1220" < "1335":
 period = 4 
if s >= "1335" < "1430":
 period = 5

print
print s
print period

writer.writerow([period])
ofile.close() 

I have another python script that grabs a student's name once they swipe their student card through a magnetic card reader and then outputs that into a CSV file.

What I want to happen is when they swipe their card their name gets imported into the CSV then the period gets imported next to it (ex. john,4 ). Then the next student will swipe their card and their name and period will be placed under the last students

 John,4
 Marcus,4

But every time a card it swiped the csv file gets erased and then the current students name is the only one left in there.

 import csv
 import datetime

 ## EQ ID

 eqid = "john" ## Output from magnetic card reader


 ## CSV writer

 ofile = open('attendance.csv', "wb")
 writer = csv.writer(ofile, delimiter=',')
 writer.writerow([eqid])
 ofile.close() 

This is just a temp mock up the final code will have both codes in it.

TL;DR - how do I have python add data to a CSV file instead of just rewriting the whole file?

But every time a card it swiped the csv file gets erased and then the current students name is the only one left in there.

This is because you are writing ( "wb" ) the file every time the card is swiped, which means a new file is created (an existing file with the same name will be erased). So You should use "ab" mode which is appending values in existing file. So the line

ofile = open('attendance.csv', "wb")

should be changed to

ofile = open('attendance.csv', "ab")

Now everytime card is swiped the values will be appended.

you can check File Operations at https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM