[英]How to read data from JSON file in ddt Python
I am using ddt with python.我正在使用带有 python 的 ddt。 I have code to read csv which looks like this -我有读取 csv 的代码,看起来像这样 -
import csv
def getcsvdata(filename):
rows = []
datafile = open(filename, "r")
reader = csv.reader(datafile)
next(reader)
for row in reader:
rows.append(row)
return rows
How can I skip rows from a 'specified number of row' to 'specified number of row'?如何从“指定的行数”跳过行到“指定的行数”? In above code next (reader) is skipping header row.在上面的代码中,下一个(读者)正在跳过 header 行。
Along-with I need to know how to read data from a JSON file?我还需要知道如何从 JSON 文件中读取数据? example JSON file-例如 JSON 文件-
{
{
"email": "amit@some.com",
"passowrd": "123@123"
},
{
"email": "tanvi@some.com",
"passowrd": "123@456"
},
{
"email": "tc.u@some.io",
"passowrd": "123@789"
}
}
The only thing you need is the library json .您唯一需要的是库json 。
Python usually gets shipped with this lib included. Python 通常随附此库。
import json
def getJsonData(filepath):
return json.load(open(filepath))
data = getJsonData("the/file/path.json")
for item in data:
print(f"email -> {item['email']}")
print(f"password -> {item['password']}")
# output:
# email -> amit@some.com
# password -> 123@123
# email -> tanvi@some.com
# password -> 123@456
# email -> tc.u@some.io
# password -> 123@789
This is what I have done using json with ddt.这就是我使用带有 ddt 的 json 所做的。
[
{
"email": "amit@some.com",
"passowrd": "123@123"
},
{
"email": "tanvi@some.com",
"passowrd": "123@456"
},
{
"email": "tc.u@some.io",
"passowrd": "123@789"
}
]
Then write your tests more like this.然后像这样写你的测试。
import unittest
from ddt import ddt, data, unpack, file_data
@ddt
class TestCase(unittest.TestCase):
"""Some test case """
@file_data('test.json')
def test_email_and_username(self, email, password):
"""This tests some stuff"""
do some assertions here
Need to use json.需要使用json。
import json
json.loads(file object)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.