Reading, Adding to and saving a CSV File using Python.
I'm having some problems with some python scripting I've been doing. The idea of the whole script is to read a csv document containing 4 coloumns of 'friends'. Being their name, address, phone number and birthday. Now, I've written out some code already, but having some issues.
- I have the code for the load_friends definition, however i开发者_JAVA百科t seems it's code just to open the csv, not to open the csv whenever the function is loaded.
- I'm really struggling to find the right tutorials to write code that adds a new line to a csv file after the function so, add_friend (name, address, ph number, birthday), enter, then it adds it to the csv.
If anyone can help with any of this, that would be most appreciated!
My code:
def load_friends():
"""Loads the friends.csv file from disk
"""
reader = csv.reader(open("friends.csv", "rb"))
for row in reader:
print row
def save_friends():
print row
def add_friend():
"""Writes a new entry to friends.csv via Python commands
"""
aCSVReader = csv.reader(open('friends.csv', 'rb'), delimiter=' ', quotechar='|')
for row in aCSVReader:
print ', '.join(row)
csv assumes newline between each line so the following should do all you need.
writer = csv.writer(open('friends.csv', 'ab'))
.....
def add_friend(name, address, ph_number, birthday):
"""write a row to the friends.csv file
"""
writer.writerow([name, address, ph_number, birthday])
load_friends open the csv, load and dump its contents to stdout.
add_friend do the same thing, and I don't understand what you are trying to do.
A more useful version could be:
def load_friends ():
with open('friends.csv', 'rb') as f:
for name, phone, address, birthday in csv.reader(f, delimiter=' ', quotechar='|'):
# do something with name, phone, etc.
def add_friend (name, phone, address, birthday):
with open('friends.csv', 'ab') as f:
newrow = [name, phone, address, birthday]
csv.writer(f, deliminter=' ', quotechar='|').writerow(newrow)
add_friend append a line to the end of file 'friends.csv' (opening with mode 'a').
Here are some tips:
In the following function, you need to fix indentation...it matters in Python. Don't know if this was an artifact of cut & paste or what, but it's an easy fix.
def load_friends():
"""Loads the friends.csv file from disk
"""
reader = csv.reader(open("friends.csv", "rb"))
for row in reader:
print row
In add_friend()
, you are opening the file for reading...you probably want to open it with mode 'ab' (append binary). If you open it in write mode ('w') the existing contents will be wiped out. Unless you are going to keep a copy of all the friends in memory and write them all out every time, this is not going to do what you expect.
Also, why have you changed the delimiter char to ' '? If it's standard CSV, this is probably not what you want either.
精彩评论