开发者

Adding data to a CSV file through Python

I've got a function that adds new data to a csv file. I've got it somewhat working. However, I'm having a few problems.

  1. When I add the new values (name, phone, address, birthday), it adds them all in one column, rather than separate columns in the same row. (Not really much idea on how to split them up in various columns...)
  2. I can only add numbers rather than string values. So if I write add_friend(blah, 31, 12, 45), it will come back saying blah is not defined. However, if I write add_friend(3,4,5,6), it'll add that to the new row—but, into a single column
  3. An objective with the function is: If you try and add a friend that's already in the csv (say, Bob), and his address, phone, birthday are already in the csv, if you add_friend(Bob, address, phone, birthday), it should state False, and not add it. However, I have no clue how to do this. Any ideas?

Here is my code:

def add_friend (name, phone, address, birthday):
    with open('friends.csv', 'ab') as f:
       newrow = [name, phone, address, birthday]
       friendwriter = csv.writer(open('friends.csv',开发者_如何转开发 'ab'), delimiter=' ',
                                   quotechar='|', quoting=csv.QUOTE_MINIMAL)
      friendwriter.writerow(newrow)
      #friendreader = csv.reader(open('friends.csv', 'rb'), delimiter=' ', quotechar='|')
      #for row in friendreader:
        #print ' '.join(row)

     print newrow


Based on your requirements, and what you appear to be trying to do, I've written the following. It should be verbose enough to be understandable.

You need to be consistent with your delimiters and other properties when reading the CSV files.

Also, try and move "friends.csv" to a global, or at least in some non-hard coded constant.

import csv

def print_friends():
    reader = csv.reader(open("friends.csv", "rb"), delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    for row in reader:
        print row

def friend_exists(friend):
    reader = csv.reader(open("friends.csv", "rb"), delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    for row in reader:
        if (row == friend):
            return True
    return False

def add_friend(name, phone, address, birthday):
    friend = [name, phone, address, birthday]
    if friend_exists(friend):
        return False

    writer = csv.writer(open("friends.csv", "ab"), delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(friend)
    return True

print "print_friends: "
print_friends()

print "get_friend: "
test_friend = ["barney", "4321 9876", "New York", "2000"]
print friend_exists(test_friend)

print "add_friend: "
print add_friend("barney", "4321 9876", "New York", "2000")


  1. It doesn't do that. What makes you think that's what it does? It's possible that the quoting scheme you really want isn't the one you specified to csv.writer: i.e., spaces delimit columns, and | is the quoting character.
  2. blah is not a string literal, "blah" is. blah without quotes is a variable reference, and the variable didn't exist here.
  3. In order to check whether a name is already in the CSV file, you have to read the whole CSV file first, checking for the details. Open the file twice: first for reading ('r'), and use csv.reader to turn that into a row-iterator and find all the names. You can add those names to a set, and then check with that set forever after.

re #3:

To get this set, you could define a function as so:

def get_people():
    with open(..., 'r') as f:
        return set(map(tuple, csv.reader(f)))

And then if you assigned the set somewhere, e.g. existing_people = get_people() you could then check against it when adding new people, as follows:

newrow = (name, phone, address, birthday)
if newrow in existing_people:
    return False
else:
    existing_people.add(newrow)
    friendwriter.writerow(newrow)


You aren't stating how experienced with Python you already are, so I am aiming this a little low - no offence intended

  1. There are several "requirements" for your homework. In general, you should ensure that one function does one thing. So, to meet all your requirements, you’ll need several functions; look at creating at least one module (i.e., a file with functions in it).

  2. A space delimiter and a | for quotes is pretty unusual. For the current file, what is the delimieter between columns? And what is used to quote/escape text? (By “escaping text”, I mean: If I have a csv file that uses commas as the column delimiter, and I want to put a sentence with commas into just one column, I need to tell the difference between a comma that means “new column” and a comma that is part of a sentence in a column. Microsoft decided that Excel would support double quotes—so "hello, sailor" became a de facto standard.

  3. If you want to know if "bob brown” is already in the file, you will need to read the whole file first before trying to insert. You can do this using 'r', then 'w'. But should you read the whole file every time you want to insert one record? What if you have a hundred records to add—should you read the whole file each time? Is there a way to store the names during the adding process?

  4. blah is not a string. It needs to be quoted to be a string literal ("blah"). blah just refers to a variable whose name is blah. If it says blah is not defined, that’s because you have not declared the variable blah to hold anything.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜