python方法记录

python方法记录

文件路径相关

  • 判断文件是否存在
import os
if(os.path.exists(file_path)): # file_path为文件路径, 判断文件是否已存在
  dosomething
# 获取当前执行文件所在文件夹
currentFolder = os.path.split(os.path.realpath(__file__))[0]
    

逻辑处理

# for循环处理,同时获取index
for index, value in enumerate([a, b, c]):
   print(index, value)

for col in range(len(testArray):
	print(testArray[col]) 
# 三目运算
test = ('a' if(test=='1') else 'b')
# 获取对象的key值
sheetTarget.keys()

python 读写excel

xlwt 库写入(仅支持xls格式, 不支持xlsx)

import xlwt
# 新建工作簿
newExcelBook = xlwt.Workbook()
# 新增sheet表
newSheet = newExcelBook.add_sheet(sheetName)
# 单元格写入数据
sheet.write(row,col,'text') # 指定单元格写入 
row2=sheet.row(1)	#在第二行创建一个行对象
row2.write(0,'data')	#向第二行第一列写入
# 保存工作簿
newExcelBook.save('./excelHandle/qw.xls')

pandas写入excel

import pandas
# 获取所有的sheet表数组
pdSheetList = pandas.read_excel(sourceFile, sheet_name=None)
# 获取指定sheet表的数据
pdSheet = pandas.read_excel(sourceFile, sheetName)
# 获取所有列名数组
colNames = pdSheet.columns.tolist()
# 对指定的sheet表,指定索引列后插入一列
pdSheet.insert(colIndex, colName, colData, allow_duplicates=True)
# 指定列数据
df['trans'] = translated_array

# 指定读写文件路径
pdWriter = pandas.ExcelWriter(fileName)
# 可多个sheet表写入, 不会覆盖
pdSheet.to_excel(pdWriter, sheet_name=sheetName, index=False)
# 将写入结果保存为excel
pdWriter.save()

xlrd库读取excel

import xlrd
# 获取excel对象
excelBook = xlrd.open_workbook(sourceFile, encoding_override="utf-8")
# 获取sheet表名数组
excelBook.sheet_names()
# 根据表明获取sheet
excelBook.sheet_by_name(sheetName)
# 根据sheet表索引获取sheet表
sheetData = excelBook.sheets()[sheetIndex]
# 获取指定索引列
sheetData.col(colIndex)
# 循环遍历获取数据(先遍历行再遍历列)
for col in range(sheetData.ncols):
    colData = sheetData.col_values(col)
    for row in range(len(colData)):
        print ('value', row, col , colData[row] )

openpyxl读写

import openpyxl
# 加载excel表
work_book = openpyxl.load_workbook(file_path) 
# 获取所有sheet表名称
names = book.sheetnames 
# 获取sheet表对象
sheet = book.worksheets[0]
sheet = book['工作表名称']
# 获取工作表名称
title = sheet1.title

#获取工作表行数/列数
rows = sheet1.max_row
cols = sheet1.max_column

# 获取某一单元格内容(从1开始计数)
cell = sheet.cell(1,2).value
cell = sheet['A1'].value #(不区分大小写)

# 创建工作簿
book = openpyxl.Workbook(encoding = 'utf-8')
# 创建sheet表 
sheet = book.create_sheet('工作表名称',0)
# 写入内容
sheet.cell(m,n,'内容1')
# 保存
book.save('excel文件名称')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值