Python csv json

题目:
1.拿到平安银行一年的股票数据 csv文件
2.里面一共244个交易日,我们读取csv文件,然后找到成交量(amount)大于1百万手的交易日的数据

3.然后把大于1百万手的那天的如下数据:
open
high
low
close
amount
写入excel文件

import csv
import xlsxwriter

def read_csv_data(file):
    list1 = []
    csvfile = open(file, 'r', newline='')
    print('开始读取数据')
    readfiles = csv.reader(csvfile)
    data = list(readfiles)
    for i in range(1, 244):
        if float(data[i][11]) > 1000000:
            list1.append(data[i])
    print("读取成功一共{}条".format(len(list1)))
    return list1

def write_to_excel(list,write_file):
    workbook = xlsxwriter.Workbook(write_file)  # 创建一个excel文件
    worksheet = workbook.add_worksheet(u'平安银行大于一百万交易量')  # 在文件中创建一个名为平安银行大于一百万交易量的sheet,不加名字默认为sheet1
    worksheet.write('A1', 'open')  # 在A1单元格写上open
    worksheet.write('B1', 'high')  # 在B1单元格写上high
    worksheet.write('C1', 'low')  # 在C1单元格写上low
    worksheet.write('D1', 'close')  # 在D1单元格写上close
    worksheet.write('E1', 'amount')  # 在E1单元格写上amount
    print('开始写入数据,一共{}条'.format(len(list)))
    for i in range(len(list)):
        worksheet.write(i + 1, 0, list[i][3])  # 使用行列的方式写上数字
        worksheet.write(i + 1, 1, list[i][4])  # 使用行列的时候第一行起始为0,所以2,0代表着第三行的第一列,等价于A4
        worksheet.write(i + 1, 2, list[i][5])
        worksheet.write(i + 1, 3, list[i][6])
        worksheet.write(i + 1, 4, list[i][11])
    workbook.close()
    print('数据写入成功')


if __name__ == '__main__':
    read_file='C:/Users/hanson/Desktop/1/000001.csv'
    data = read_csv_data(read_file)
    write_file='C:/Users/hanson/Desktop/1/000001.xlsx'
    write_to_excel(data,write_file)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

总结:写代码一定要灵活,可以不写死的代码就不要写死

猜你喜欢

转载自blog.csdn.net/SeeUa/article/details/88831291