前言
CSV, Comma Separated Values, 是一种常见的文件格式。
python中提供了csv模块,对其进行操作。
以下程序代码基于python2.7.
python的csv模块,属于自带module,提供了reader, writer和DictReader, DictWriter来读写文件,不同的是,后者顾名思义,基于Dict字典来进行读写。
1. 小程序python写文件:
import csv
def csv_writer():
with open('sample.csv', 'wb') as csvfile:
mywriter = csv.writer(csvfile)
mywriter.writerow(['One', 'Two', 'Three'])
mywriter.writerow(['Cat', 'Dog', 'Horse'])
csv_writer()
|
输出结果:
2. 小程序python读文件:
def csv_reader():
with open('sample.csv', 'rb') as csvfile:
myreader = csv.reader(csvfile)
for row in myreader:
print row
csv_reader()
|
输出结果:
['One', 'Two', 'Three']
['Cat', 'Dog', 'Horse']
|
程序1,2生成的csv文件没有header,也就是Column Name,下面的使用Dict来进行读写。
3. 小程序python写header csv:
def dict_csv_writer():
with open('dictsample.csv', 'wb') as dictcsvfile:
fileds = ['Name', 'Age', 'City']
mydict_writer = csv.DictWriter(dictcsvfile, fieldnames=fileds)
mydict_writer.writeheader()
mydict_writer.writerow({'Name':'Jack', 'Age':20, 'City':'Shanghai'})
mydict_writer.writerow({'Name':'Alice', 'Age':30, 'City':'Beijing'})
mydict_writer.writerow({'Name':'Ben', 'Age':25, 'City':'Hangzhou'})
dict_csv_writer()
|
输出结果:
4. 小程序python读header csv
def dict_csv_reader():
with open('dictsample.csv', 'rb') as dictcsvfile:
mydict_reader = csv.DictReader(dictcsvfile)
for row in mydict_reader:
print row
dict_csv_reader()
|
输出结果:
{'City': 'Shanghai', 'Age': '20', 'Name': 'Jack'}
{'City': 'Beijing', 'Age': '30', 'Name': 'Alice'}
{'City': 'Hangzhou', 'Age': '25', 'Name': 'Ben'}
|
讨论
以上是基本读写文件,下面讨论几点细节。
1. csv文件,有一些格式化的属性,比方说,分隔符delimiter, 换行符lineterminator,引用字符quotechar等等,写程序的时候,可以选择在csv.reader()和csv.writer()函数中单独设置,举例来说,
mywriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
|
输出结果
One Two |Three Half|
Cat Dog Horse
|
这些属性,也可以被包含着一个叫做Dialect的类中,这样,使用时,只要指定
mywriter = csv.writer(csvfile, dialect='excel')
|
可以运行csv.list_dialects()来返回目前支持的dialects,或者自己包装一个Dialect类,来代替。
以下附录完整代码。
import csv
def csv_writer():
with open('sample.csv', 'wb') as csvfile:
mywriter = csv.writer(csvfile)
mywriter.writerow(['One', 'Two', 'Three Half'])
mywriter.writerow(['Cat', 'Dog', 'Horse'])
csv_writer()
def csv_reader():
with open('sample.csv', 'rb') as csvfile:
myreader = csv.reader(csvfile)
for row in myreader:
print row
csv_reader()
def dict_csv_writer():
with open('dictsample.csv', 'wb') as dictcsvfile:
fileds = ['Name', 'Age', 'City']
mydict_writer = csv.DictWriter(dictcsvfile, fieldnames=fileds, dialect='excel')
mydict_writer.writeheader()
mydict_writer.writerow({'Name':'Jack', 'Age':20, 'City':'Shanghai'})
mydict_writer.writerow({'Name':'Alice', 'Age':30, 'City':'Beijing'})
mydict_writer.writerow({'Name':'Ben', 'Age':25, 'City':'Hangzhou'})
dict_csv_writer()
def dict_csv_reader():
with open('dictsample.csv', 'rb') as dictcsvfile:
mydict_reader = csv.DictReader(dictcsvfile)
for row in mydict_reader:
print row
dict_csv_reader()
|
Wish you happy with python:)