python实现多种格式文件的读取

文件结构类似于此:

pytest/tools/read_json.py

pytest/data/data.json

1.json数据的读取

read_json.py

import json
#从json文件读取json格式的数据
def read_json(filename):
    filepath="../data/"+filename
    with open(filepath, "r", encoding="utf-8")as f:
        return json.load(f)

2.CSV数据的读取

read_csv.py

import csv
def read_csv(self):
    ret_list=[]
    with open("../data/data.csv","r") as f:
        csv_context=csv.reader(f)
        for csv_con in csv_context:
            ret_list.append(csv_con)
    return ret_list

3.TXT文件的读取(类似csv):

read_txt.py

import os
def read_txt(filename):
    filepath = "../data/" + filename
    if os.path.exists(filepath):
        with open(filepath, "r", encoding="utf-8")as f:
            data=f.readlines()
        return data

4.XML文件的读取:

read_xml.py

from xml.dom import minidom
def read_xml(self,file_path,firstnode,twonode):
    root=minidom.parse(file_path)
    firstnode=root.getElementsByTagName(firstnode)[0]
    secondnode=firstnode.getElementsByTagName(twonode)[0].firstChild.data
    return secondnode

5.yaml文件的读取

read_yaml.py

import yaml
def read_yaml(filename):
    filepath = "../data/" + filename
    with open(filepath, "r", encoding="utf-8")as f:
        return yaml.load(f)

备注:解析数据的方法根据实际需要进行格式化解析.

你可能感兴趣的:(09web自动化)