简体   繁体   English

使用Python读取,添加和保存CSV文件。

[英]Reading, Adding to and saving a CSV File using Python.

I'm having some problems with some python scripting I've been doing. 我在做一些python脚本时遇到问题。 The idea of the whole script is to read a csv document containing 4 coloumns of 'friends'. 整个脚本的想法是读取包含4个“朋友”对话的csv文档。 Being their name, address, phone number and birthday. 他们的名字,地址,电话号码和生日。 Now, I've written out some code already, but having some issues. 现在,我已经写了一些代码,但是有一些问题。

  1. I have the code for the load_friends definition, however it seems it's code just to open the csv, not to open the csv whenever the function is loaded. 我有用于load_friends定义的代码,但是似乎只是打开csv的代码,而不是每次加载函数时都打开csv的代码。
  2. 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. 我真的很难找到合适的教程来编写代码,以便在函数之后在csv文件中添加新行,然后输入add_friend(名称,地址,ph值,生日),然后将其添加到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. csv假设每行之间都使用换行符,因此以下内容将满足您的所有需求。

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])

Here are some tips: 这里有一些提示:

In the following function, you need to fix indentation...it matters in Python. 在以下函数中,您需要修复缩进...这在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). add_friend() ,您正在打开文件以供阅读...您可能希望以'ab'模式(附加二进制文件)打开它。 If you open it in write mode ('w') the existing contents will be wiped out. 如果以写模式('w')打开它,现有内容将被清除。 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 ' '? 另外,为什么还要将定界符char更改为''? If it's standard CSV, this is probably not what you want either. 如果是标准CSV,则可能也不是您想要的。

load_friends open the csv, load and dump its contents to stdout. load_friends打开csv,将其内容加载并转储到stdout。

add_friend do the same thing, and I don't understand what you are trying to do. add_friend也做同样的事情,但我不明白您要做什么。

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'). add_friend在文件'friends.csv'的末尾添加一行(以模式'a'打开)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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