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 json
with open('test.json',"r") as f:
json_dic = json.load(f)
print(json_dic["bigberg"])
4.csv文件读写
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 csv
with open("example.csv",'r') as f:
reader = csv.reader(f)
for row in reader:
print(reader.line_num, row)
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.minidom
def 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())