用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(">>数据写入成功")