python文件写入excel_Python文件读写(csv、excel)

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')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值