import csv
def write_csv(filePath,data):
with open(filePath,mode="w",newline="",encoding="utf-8") as csvfile:
writer=csv.writer(csvfile);
for line in data:
writer.writerow(line);
def read_csv(filePath):
data=[];
with open(filePath,mode="r",encoding="utf-8") as csvfile:
reader=csv.reader(csvfile);
for line in reader:
data.append(line)
return data;
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.worksheet.worksheet import Worksheet
def write_excel(filepath,sheetName,header,data):
wb=Workbook();
ws=wb.create_sheet(sheetName);
#写入header
ws.append(header)
row=1
for lineData in data:
row=row+1;
col=1
for value in lineData.values():
ws.cell(row=row,column=col,value=value)
col=col+1;
wb.save(filepath)
def read_excel(filePath,sheetName):
wb=load_workbook(filePath)
ws:Worksheet=wb[sheetName]
data=[];
for x in range(2,ws.max_row+1):
dic={}
for y in range(1,ws.max_column+1):
dic[ws.cell(1,y).value]=ws.cell(row=x,column=y).value
data.append(dic)
return data;
调用:
from ToolUtils.csv_handler import read_csv,write_csv
import os
filePath=os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),"data\\test.csv")
testdata=(["编号","标题"],["1","登录成功1"],["2","登录成功2"],["3","登录成功3"])
write_csv(filePath,testdata)
readData=read_csv(filePath)
for line in readData:
print(line)
from ToolUtils.excel_handler import write_excel,read_excel
filePath=os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),"data\data.xlsx")
header=["title","method","url"]
testData=[{"tile":"用户注册1","method":"get","url":"http://www.baidu"},{"title":"用户注册2","method":"post","url":"http//www.badu.com"},
{"title":"用户注册3","method":"post","url":"http://www.baidu.com"}]
write_excel(filePath,"MySheet",header,testData)
print(read_excel(filePath,"MySheet"))