码迷,mamicode.com
首页 > 编程语言 > 详细

python读写csv文件

时间:2018-10-06 11:56:10      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:file   lin   class   color   reader   写入   limit   char   read   

csv文件格式简单,在一些场合使用更加方便。

1. 读csv文件

‘‘‘
读取CSV文件
‘‘‘
def readCsvFile(filename):
    # 此处python2.x中是"rb",python3.x中是"r"
    with open(filename, "r") as f:
        spamreader = csv.reader(f, delimiter= , quotechar=|)
        for row in spamreader:
            print(row[0].split(,))

依赖的库:

# python标准库
import csv

代码很简单的,唯一需要注意的是python2.x与python3.x中,文件打开方式的不同。

python2.x  open mode = “rb”

python3.x  open mode = “r”

 

2. 写csv文件

 1 ‘‘‘
 2 写CSV文件
 3 @filename 文件名
 4 @header   列头
 5 @content  内容
 6 ‘‘‘
 7 def writeCsvFile(filename, header, content):
 8     # 此处python2.x中是"wb",python3.x中是"w"
 9     with open(filename, "w") as f:
10         f.write(,.join(header) + \n)
11 
12         for line in content:
13             f.write(,.join(line) + \n)

使用普通的open,write函数就可以完成csv的写入。

csv是以逗号为分隔符的,所以写入的内容要添加好分号。

write函数也不会自动添加换行符,需要手动添加。

 

需要注意的是python2.x与python3.x中,文件打开方式的不同。

python2.x  open mode = “wb”

python3.x  open mode = “w”

python读写csv文件

标签:file   lin   class   color   reader   写入   limit   char   read   

原文地址:https://www.cnblogs.com/zhugaopeng/p/9746756.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!