1、csv读写的文件
import csv
file='C:\\Users\\Lee\\Desktop\\a.csv'
with open(file,'r') as f:
data=csv.reader(f)#读文件,为可迭代对象
#print(list(data)[1:]) #转为list,然后取1行到最后(未取0行)
all_user=[]
for user in data:
all_user.append(user)
print(user)
print(all_user)
file2='C:\\Users\\Lee\\Desktop\\b.csv'
with open(file2,'w',newline='') as f:
data=csv.writer(f)
data.writerows(all_user)
2、读写excel(*.xls)
2.1读
importxlrd, os#打开一个excel
data =xlrd.open_workbook(file)#通过sheet名称打开#table = data.sheet_by_name("login")#通过index打开,0开始
table =data.sheet_by_index(0)#获取整行和整列的值(数组)#row_value = table.row_values(0)#col_value = table.col_values(0)
#获取行数和列数#nrows = table.nrows#ncols = table.ncols
#单元格#cell_A1 = table.cell(0, 0).value#cell_C4 = table.cell(2, 3).value
#使用行列索引#cell_A1 = table.row(0)[0].value#cell_A2 = table.col(1)[0].value
#获取数据组成([row1],[row2])
#e_list = []#for n_row in range(1, table.nrows):#e_list.append(table.row_values(n_row))#e_tuple = tuple(e_list)
#print(e_tuple)#print(table.cell(0, 0).value)#print(table.row(0)[0].value)#print(table.col(1))
e_list=[]
header_row=table.row_values(0)for n_row in range(1, table.nrows):
e_list.append(dict(zip(header_row, table.row_values(n_row))))#print(zip(header_row, table.row_values(n_row)))#zip函数接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表。[, ]
print(e_list)
2.2写
import xlwt
# 新建一个excel对象
wb = xlwt.Workbook()
# 新建一个名为text的sheet页
sh = wb.add_sheet("test")
# 前两个参数为单元格位置
for i in range(5):
sh.write(i, 0, i)
# 目前只能保存成xls后缀
wb.save("data.xls")
2.3更新
from xlrd importopen_workbookfrom xlutils.copy importcopy#打开文件
rb = open_workbook("data.xls")#复制
wb =copy(rb)#选取表单
s = wb.get_sheet("login")#写入数据
s.write(3, 0, 'tom')
s.write(3, 1, '333')
s.write(3, 2, 'success')#保存
wb.save('data.xls')