Python基础(Day 13)(csv、json、excel 的读写)

知识点总结:
1. csv格式操作
2. json格式操作
3. excel格式操作


csv操作

csv读取
import csv
from collections import namedtuple


# 将csv文件视为文本文件的普通读取方法
def read():
    with open('data.csv', 'r', encoding='utf8') as f:
        header = f.readline()
        print(header)

        for line in f:
            print(line)

# 使用csv模块的读取方法
def read_by_csv_reader():
    with open('data.csv', 'r', encoding='utf8') as f:
        reader = csv.reader(f)
        header = next(reader)
        print(header)
        for row in reader:
            print(row)

# 通过csv模块将读取到的数据封装成nametuple
def read_csv_by_nametuple():
    with open('data.csv', 'r', encoding='utf8') as f:
        reader = csv.reader(f)
        header = next(reader)
        Row = namedtuple('Row', header)
        print(header)
        for r in reader:
            row = Row(*r)
            print(f'id:{row.id}\tname:{row.name}\tprice:{row.price}')

# 通过csv的DictReader方法读取
def read_csv_by_dict():
    with open('data.csv', 'r', encoding='utf8') as f:
        reader = csv.DictReader(f)
        for row in reader:
            print(f'{row.get("id")} -> {row.get("name")} -> {row.get("price")}')


if __name__ == '__main__':
    read_csv_by_dict()
CSV写文件
import csv


# 方法一
def wirte_csv():
    header = ['id', 'name', 'price']
    rows = [
        (1, 'Python', 12),
        (2, 'Java', 11),
        (3, 'C++', 13),
        (4, 'Go', 15)
    ]
    with open('books.csv', 'w', encoding='utf8', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(header)
        writer.writerows(rows)


# 方法二
def wirte_csv_by_dict():
    header = ['id', 'name', 'price']
    rows = [
        {'id':1, 'name':'C', 'price':12},
        {'id':2, 'name':'C++', 'price':12},
        {'id':3, 'name':'C+++', 'price':12},
        {'id':4, 'name':'C#', 'price':12},

    ]
    with open('books.csv', 'w', encoding='utf8', newline='') as f:
        writer = csv.DictWriter(f, header)
        writer.writeheader()
        writer.writerows(rows)




if __name__ == '__main__':
    wirte_csv_by_dict()

json操作

import json

str_data = ''

# djson.dumps() 将dict转为string
def json_write():
    global str_data
    data = {'ID': 2, 'NAME': '西游记', 'URL': 'www.xiyouji.cn'}
    str_data = json.dumps(data)
    print(str_data)

# json.loads() 将str转为dict
def json_read():
    json_data = json.loads(str_data)
    print(json_data)
    return json_data

# dump到文件
def json_to_file():
    with open('jsondata.txt', 'w', encoding='utf8') as f:
        json.dump(json_read(), f)

# 从文件加载数据成json格式
def json_from_file():
    with open('jsondata.txt', 'r', encoding='utf8') as f:
        json_data = json.load(f)
        print(json_data)
        return json_data

# 注意null-None, true-True, false-False 的格式不同
def json_type_diff():
    data = {'a': None, 'b': False, 'c': True}
    str_data = json.dumps(data)
    print(str_data)

if __name__ == '__main__':
    json_write()
    json_read()
    json_to_file()
    json_from_file()
    json_type_diff()

excel操作

需按装xlrd模块

import xlrd

def xl_read():
    book = xlrd.open_workbook('product.xls')
    for sheet in book.sheets():
        print(sheet.name)
        print(sheet.nrows)
        for i in range(sheet.nrows):
            print(sheet.row_values(i))
发布了45 篇原创文章 · 获赞 2 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_22096121/article/details/103341953
今日推荐