1.概述
在平时自动化测试工作中,经常会用python对一些文件进行读写操作。其中使用最多的文件格式,就是txt, log, json, csv, xml, zip, tar, gz, rar, excel,这十种文件格式。
其中txt, log, json, csv, xml这五种格式,使用python标准库就可以操作。
2.txt, log文件读写
.txt和.log文件的读写方式相同,下面只以.txt文件做为例子。
1)写:
with open("test.txt","w") as f:
f.write("test string")2)读:
with open("test.txt","r") as f:
print(f.read())3)注意事项:
一般文件的模式
r: 以读方式打开
w : 以写方式打开,
a: 以追加模式打开 (从 EOF 开始, 必要时创建新文件)多媒体mp3,mp4,或者包含特殊字符的模式
rb: 以二进制读模式打开
wb: 以二进制写模式打开
ab : 以二进制追加模式打开其它:
r+,w+,a+,rb+,wb+,ab+
4)Python读取大文件(GB级别):
#内存分配交给python解释器处理,读取效率很高,且占用资源少with open("test.txt","r") as f: for line in f:
print(line)3.json文件读写
1)写:
import json
test_dict = {'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]}#dumps 将数据转换成字符串json_str = json.dumps(test_dict,indent=4,sort_keys=True)with open('test.json',"w") as f:
f.write(json_str)2)读:
import jsonwith open('test.json',"r") as f:
json_dic = json.load(f)
print(json_dic["bigberg"])4.csv文件读写
使用csv里的writer类
1)写:
import csv# 使用数字和字符串的数字都可以datas = [['name', 'age'],
['Bob', 14],
['Tom', 23],
['Jerry', '18']]with open('example.csv', 'w', newline='') as f:
writer = csv.writer(f) for row in datas:
writer.writerow(row)2)读:
import csvwith open("example.csv",'r') as f:
reader = csv.reader(f) for row in reader:
print(reader.line_num, row)使用csv里的Dictwriter类
1)写:
import csv
headers = ['name', 'age']
datas = [{'name':'Bob', 'age':23},
{'name':'Jerry', 'age':44},
{'name':'Tom', 'age':15}
]with open('example.csv', 'w', newline='') as f: # 表头在这里传入,作为第一行数据
writer = csv.DictWriter(f, headers)
writer.writeheader() for row in datas:
writer.writerow(row)2)读:
import csv filename = 'example.csv'with open(filename) as f: reader = csv.DictReader(f) for row in reader: # name是表第一行的某个数据,作为key name = row['name'] print(name)
5.xml文件读写
1)写:
#coding=utf-8# 生成xml文件import xml.dom.minidomdef GenerateXml():
impl = xml.dom.minidom.getDOMImplementation()
dom = impl.createDocument(None, 'CONFIG_LIST', None)
root = dom.documentElement
employee = dom.createElement('COMP')
root.appendChild(employee)
nameE = dom.createElement('path')
nameE.setAttribute("value", "aaaaaaaaaaa") # 增加属性
nameT = dom.createTextNode('linux')
nameE.appendChild(nameT)
employee.appendChild(nameE)
f = open('config_new.xml', 'a')
dom.writexml(f, addindent=' ', newl='\n')
f.close()
GenerateXml()2)读:
import xml.etree.cElementTree as ET
tree = ET.parse("config_new.xml")
root = tree.getroot()
COMP = root.findall('COMP')[0]#方法通过tag名字或xpath匹配第一层子元素print("Tag:", COMP.tag, "Attributes:", COMP.attrib, "Text:", COMP.text.strip(), "Tail:", COMP.tail)
path = COMP.findall("path")[0]#方法通过tag名字或xpath匹配第一层子元素print("Tag:", path.tag, "Attributes:", path.attrib, "Text:", path.text.strip(), "Tail:", path.tail)#Element类和ElementTree类都有iter()方法可以递归遍历元素/树的所有子元素for child in tree.iter(tag='path'): #tree是ElementTree对象
print("Tag:", child.tag, "Attributes:", child.attrib, "Text:", child.text.strip(
作者:Godric_wsw
链接:https://www.jianshu.com/p/211356a8f4cb
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦