如何在ddt Python中从JSON文件读取数据

2024-06-24 13:31:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我将ddt与python一起使用。 我有读取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

如何从“指定行数”跳到“指定行数”? 在上面的代码中,下一个(读取器)跳过标题行

我还需要知道如何从JSON文件中读取数据? 示例JSON文件-

{
    {
        "email": "amit@some.com",
        "passowrd": "123@123"
    },
    {
        "email": "tanvi@some.com",
        "passowrd": "123@456"
    },
    {
        "email": "tc.u@some.io",
        "passowrd": "123@789"
    }
}

Tags: 文件csv代码importcomjsonemailsome
3条回答

需要使用json

import json
json.loads(file object)

这就是我使用json和ddt所做的

[
    {
        "email": "amit@some.com",
        "passowrd": "123@123"
    },
    {
        "email": "tanvi@some.com",
        "passowrd": "123@456"
    },
    {
        "email": "tc.u@some.io",
        "passowrd": "123@789"
    }
]

然后像这样编写测试

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

您只需要库json

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

相关问题 更多 >