Skip to content Skip to sidebar Skip to footer

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, ad

Solution 1:

csv assumes newline between each line so the following should do all you need.

writer = csv.writer(open('friends.csv', 'ab'))  
.....      
defadd_friend(name, address, ph_number, birthday):
    """write a row to the friends.csv file
    """
    writer.writerow([name, address, ph_number, birthday])

Solution 2:

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:

defload_friends ():
    withopen('friends.csv', 'rb') as f:
        for name, phone, address, birthday in csv.reader(f, delimiter=' ', quotechar='|'):
            # do something with name, phone, etc.defadd_friend (name, phone, address, birthday):
    withopen('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').

Solution 3:

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.

defload_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.

Post a Comment for "Reading, Adding To And Saving A Csv File Using Python."