整理了一下python对文件的一些常见操作方法
暂时先写一下对excel文件的基本操作,例如新建,写入内容,保存。
先贴代码,注释很详细的。
#coding=utf-8 import xlwt import xlrd try: # 创建excel文件 filename=xlwt.Workbook() # 给工作表命名,test sheet=filename.add_sheet("test") # 写入内容,第4行第3列写入‘张三丰’ hello=u'张三丰' sheet.write(3,2,hello) # 指定存储路径,如果当前路径存在同名文件,会覆盖掉同名文件 filename.save("D:/test1.xls") except Exception,e: print(str(e))
后面对应用到自动化持续集成工作是必不可少的准备工作,数据驱动,持续集成,都需要对文件进行读写操作的。
在上面的基础上,读取该文件刚刚写入的内容,并打印出来
实现代码如下:
#coding=utf-8 import xlwt import xlrd try: # 创建excel文件 filename=xlwt.Workbook() # 给工作表命名,test sheet=filename.add_sheet("test") # 写入内容,第4行第3列写入‘张三丰’ hello=u'张三丰' sheet.write(3,2,hello) # 指定存储路径,如果当前路径存在同名文件,会覆盖掉同名文件 filename.save("D:/test1.xls") except Exception,e: print(str(e)) # 找到读取文件 filename='D:/test1.xls' # 打开excel文件 date=xlrd.open_workbook(filename) # 根据工作表名称,找到指定工作表 by_index(0)找到第N个工作表 sheet=date.sheet_by_name('test') # 读取第四行第三列内容,cell_value读取单元格内容,指定编码 value=sheet.cell_value(3,2).encode('utf-8') print(value)