python csv存储与读取

csv文件格式是一种通用的电子表格和数据库导入导出格式,是Python csv模块封装了常用的功能。

    1. csv的读取
import csv
#读取csv
def read_cvs(cvs_name):
    with open("some.cvs", 'rb') as f:
        f_csv = csv.reader(f)
        for row in f_csv:
            print(row[1])   #打印csv的某一列
# 'xiaoming'
#'xiaohong'
#'xiaozhang'
#'xiaoli'

# 写入csv
import csv
with open('some.csv', 'wb') as f:      # 采用b的方式处理可以省去很多问题
    writer = csv.writer(f)
    writer.writerows([1,2,3,4,5])
    1. csv还提供了一种类似于字典方式的读写
#字典式读取csv
import csv
def read_cvs(cvs_name):
    with open("some.cvs", 'rb') as f:
        f_csv = csv.DictReader(f)
        for row in f_csv:
            print(row)    # 以字典的方式打印csv的某一列

#{'class': '1', 'name': 'xiaoming', 'sex': 'male', 'height': '168', 'year': '23'}
#{'class': '1', 'name': 'xiaohong', 'sex': 'female', 'height': '162', 'year': '22'}
#{'class': '2', 'name': 'xiaozhang', 'sex': 'female', 'height': '163', 'year': '21'}
#{'class': '2', 'name': 'xiaoli', 'sex': 'male', 'height': '158', 'year': '21'}


# 字典式写入csv
import csv
with open('names.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

    1. csv添加表头
 # 以字典的方式写入cvs rows数据 (第一次写入)
    def write_csv():
        headers = ['class', 'name', 'sex', 'height', 'year']
        rows = [
            {'class': 1, 'name': 'xiaoming', 'sex': 'male', 'height': 168, 'year': 23},
            {'class': 1, 'name': 'xiaohong', 'sex': 'female', 'height': 162, 'year': 22},
            {'class': 2, 'name': 'xiaozhang', 'sex': 'female', 'height': 163, 'year': 21},
            {'class': 2, 'name': 'xiaoli', 'sex': 'male', 'height': 158, 'year': 21},
        ]
        with open(self.cvs_dir+cvs_name, 'w', newline='') as f:
            f_csv = csv.DictWriter(f, headers)
            f_csv.writeheader()
            f_csv.writerows(rows)

你可能感兴趣的:(python csv存储与读取)