目錄
- 一、通過創建.ini或.conf文件讀取
- 二、通過yaml文件讀取
- 三、通過excel讀取
一、通過創建.ini或.conf文件讀取
1、創建一個config.ini或者.conf文件,這種方法就是ini文件的讀取,如下
[api]
url = www.taobao.com
method = get
[mysql]
db=hello
port=3306
2、使用python的configparser庫讀取,代碼如下
from configparser import ConfigParser
import os
conn=ConfigParser()
#獲取ini文件的路徑
file_path = os.path.join(os.path.abspath('.'),'config.ini')
conn.read(file_path)
url=conn.get('api','url')
method=conn.get('api','method')
port=conn.get('mysql','port')
print(url,method,port)
3、運行得到如下的值,讀取成功
www.taobao.com get 3306
二、通過yaml文件讀取
1、首先創建一個.yaml文件,這里我創建login_data.yaml,具體數據格式大家自行google,這里我隨便編寫一些數據
-
caseid: 1
method: post
title: 正常登錄
url: api/v1/login
data:
username: test
password: 123456
headers:
Content-Type: application/json
User-Agent: Mozilla/5.0
expected: 0
2、命令行通過pip install pyyaml安裝yaml包,直接上代碼
import yaml
def read_file(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
res = yaml.load(f,Loader=yaml.FullLoader)
return res
if __name__ == '__main__':
d = read_file(r'..\test_data\login\login_data.yml')
print(d)
3、運行結果如下,是一個列表
[{'caseid': 1, 'method': 'post', 'title': '正常登錄', 'url': 'api/v1/login', 'data': {'username': 'test', 'password': 123456}, 'headers': {'Content-Type': 'application/json', 'User-Agent': 'Mozilla/5.0'}, 'expected': 0}]
三、通過excel讀取
1、創建一個excel文件,隨便寫點數據

2、通過pandas讀取,當然還有其他的很多庫,本人覺得這個最方便,直接轉化成dict方便使用
import pandas
def excel_to_dic(filename):
df = pandas.read_excel(filename)
data_list = []
for i in df.index.values:
data = df.iloc[i, [j for j in range(len(df.keys()))]].to_dict()
data_list.append(data)
return data_list
if __name__ == '__main__':
file = r'C:\aaa.xlsx'#之前創建的文件地址
data = excel_to_dic(file)
print(data)
3、運行結果如下
[{'name': 'zhangsan', 'phone': 13112345678, 'age': 20}, {'name': 'lisi', 'phone': 13867543678, 'age': 30}, {'name': 'wangwu', 'phone': 15967845632, 'age': 40}]
可以看出結果是把excel表中的每一行數據轉換成了一個dict,更加方便以后使用!!!
到此這篇關于python讀取測試數據的多種方式的文章就介紹到這了,更多相關python讀取測試數據內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- 從零學python系列之從文件讀取和保存數據
- python讀取excel指定列數據并寫入到新的excel方法
- python讀取txt文件并取其某一列數據的示例
- Python如何讀取MySQL數據庫表數據
- python讀取文本中數據并轉化為DataFrame的實例
- python 讀取.csv文件數據到數組(矩陣)的實例講解
- python讀取json文件并將數據插入到mongodb的方法
- Python實現讀取txt文件中的數據并繪制出圖形操作示例
- python讀取各種文件數據方法解析