第十八天:CSV、JSON、Excel、SQLite

一、CSV文件

1、读取

  • reader = csv.reader(打开的file对象), reader为可迭代对象

2、用namedtuple映射列名

with open('apple.csv') as f:
    reader = csv.reader(f)
    headers = next(reader)  # 一般第一行是属性名
    Row = namedtuple('Row',headers)
    for r in reader:
        row = Row(*r)
        print(row)

3、读取到字典表

with open('a.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row)

二、JSON模块

  • json.dumps() 转换成json类型的字符串
  • json.loads() 从json字符串读取
  • json.dump(data,file) 写json文件
  • json.load(file) 读json文件
  • json中的false为None

    三、excel 模块

    使用xlrd模块

  • a = xlrd.open_workbook(file) 读取excel文件
  • for sheet in book.sheets(): 遍历文件中的工作簿
  • book.sheet_by_index() 按下标找工作簿
  • book.sheet_by_name() 按名称找工作簿
  • sheet.name 工作簿名
  • sheet.nrows 数据行数
  • sheet.row_values(index) 获取索引指定的数据行

猜你喜欢

转载自www.cnblogs.com/linyk/p/11530342.html