Python自动化测试之文件操作

1、读、写、追加文件

读:打开文件  r    读写:r+

写:w 可写不可读  清空原文件   写读:w+ 清空文件

追加:a+  可以读写,文件不存在自动创建

 

 

 

练习读txt文件类容:

#-*- coding : utf-8 -*-
file = open(r'C:\\Users\Administrator\PycharmProjects\\untitled\\test\致橡树.txt')
with file:
data = file.read()
print(data)

 

 读取excel文件类容:

读取Excel是需要模块openpyxl:

 

关闭文件操作: file.close()

文件句柄的关系,open过后需要关闭

读取文件一行信息:file.readline()

读取文件全部信息信息:file.readlines()

 

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
'''
@project:
@name: test_excel
@date: 2019/12/4 11:51
'''
from openpyxl import load_workbook
import openpyxl
def main(path_url=r"D:\untitled\test\700URLV1.xlsx"):
L = []
workbook = load_workbook(path_url) # 找到需要xlsx文件的位置
booksheet = workbook.active # 获取当前活跃的sheet,默认是第一个sheet
for row in booksheet.rows:
for col in row:
if col.value:
L.append(col.value)
return L
if __name__ == '__main__':
print(main())

 

 

 

 

 

文件写入类容操作练习:

#-*- coding : utf-8 -*-
file = open('C:\\Users\Administrator\PycharmProjects\\untitled\\test\致橡树.txt','w')
for i in range(20):
file.write(str(i))
file.close()

file = open('C:\\Users\Administrator\PycharmProjects\\untitled\\test\致橡树.txt','r')
print(file.read())
file.close()

 

 

创建文件 操作:

 

 

 

写入文件,换行操作:运用"\n"

#-*- coding : utf-8 -*-
file = open('C:\\Users\Administrator\PycharmProjects\\untitled\\test\致橡.txt','w')
for i in range(5):
file.write(str(i) + '\n')
file.close()

file = open('C:\\Users\Administrator\PycharmProjects\\untitled\\test\致橡.txt','r')
print(file.read())
file.close()






 

posted @   宽崽  阅读(547)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示