用python读写文件

用python读写excel

下面是用Python将数据写入excel的方法

#coding: utf-8 

import pymysql
import xlrd,xlwt
import os

workbook = xlwt.Workbook()
sheet = workbook.add_sheet("sheet")
sheet.write(0,0,1)
#第一个0代表第0行,第二个0代表第0列,1代表写入数据为1.
workbook.save("excel1.xls")

#来个狠得,写入数据方法2
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("员工信息表")
header = [i for i in emplist[0]]
for i in range(len(header)):
    sheet.write(0, i, header[i])
content = [[v for v in d.values()] for d in emplist]
for rowindex in range(1, len(content) + 1):
    for colindex in range(len(header)):
        sheet.write(rowindex, colindex, content[rowindex -1][colindex])
workbook.save("emp.xls")

下面是用Python读excel的程序

#coding: utf-8

import pymysql
import xlrd,xlwt
import os

workbook = xlrd.open_workbook("excel1.xls")
sheetname = workbook.sheet_names()
sheet = workbook.sheet_by_name(sheetname[0])
a= sheet.cell_value(0,0)
print(a)

用python读写csv

import csv

# 使用csv.reader函数读取文件
with open("data/data.csv",encoding="utf-8") as file:
    # reader 相当于二维列表
    reader = csv.reader(file)
    # print(reader)
    # 使用for循环遍历
    for i in reader:
        print(i)
#写数据
# 标题行
header = ["姓名","年龄","电话"]
# 数据行
data = [("张三",28,"13888888888"),("李四",18,"13888888888"),("王五",32,"13888888888")]
# 写入数据到csv
with open("data/mydata.csv",mode="w",encoding="utf-8",newline="") as file:
    # 使用csv.writer函数写文件
    write = csv.writer(file)
    # print(write)
    # 写入标题行数据(使用writerow方法写入单行数据)
    write.writerow(header)
    print(">>标题行写入成功")
    # 写入数据
    write.writerows(data)
    print(">>数据写入成功")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值