使用Python读取,添加和保存CSV文件. [英] Reading, Adding to and saving a CSV File using Python.
本文介绍了使用Python读取,添加和保存CSV文件.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在做一些python脚本时遇到一些问题.整个脚本的想法是读取一个包含4个朋友"对话的csv文档.是他们的名字,地址,电话号码和生日.现在,我已经写了一些代码,但是有一些问题.
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.
- 我有用于load_friends定义的代码,但是似乎只是打开csv的代码,而不是每次加载函数时都打开csv的代码.
- 我真的很难找到合适的教程来编写代码,以便在函数之后在csv文件中添加新行,然后输入add_friend(名称,地址,ph值,生日),然后将其添加到CSV.
如果任何人都可以提供帮助,将不胜感激!
If anyone can help with any of this, that would be most appreciated!
我的代码:
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假定每行之间都使用换行符,因此以下内容将满足您的所有需求.
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])
这篇关于使用Python读取,添加和保存CSV文件.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文