Pythonユーティリティスクリプト

2818 ワード

1、yamlファイルを読み込む:test.yaml:
testinfo:
  - testcase1: test1
    test2: test2
  - testcase2: test1
    test2: test2

test.py:
import yaml

def load_yaml_file(yaml_file):
    try:
        with open(yaml_file, encoding='utf-8') as f:
            file_stream = yaml.load(f)
            return file_stream
    except FileNotFoundError:
        pass

if __name__=='__main__':
    file_content=load_yaml_file(r'test.yaml')
    print(file_content.get('testinfo'))

出力:
[{'test2': 'test2', 'testcase1': 'test1'}, {'testcase2': 'test1', 'test2': 'test2'}]

2、Excelファイルを読み取る:
from xlrd import open_workbook  #xlrd:  excel    

class ReadExcel:
    def __init__(self, path, index=0):
        #path excel      ,index         
        self.book = open_workbook(path)
        self.sheet = self.book.sheet_by_index(index)


    def get_excel_data(self, row, col):#         row,  col       
        return self.sheet.cell(row, col).value

    def get_nrows(self):#     
        return self.sheet.nrows

    def get_ncols(self):#     
        return self.sheet.ncols

3、読み取りiniプロファイル:
import configparser  #configParser           

class ReadConfig:
    def __init__(self, path):
        #path            
        self.config_file_path = path
        self.conf = configparser.ConfigParser()
        self.conf.read(self.config_file_path)

    def get_data_file_path_data(self, dataname): #  section data_file_path  key dataname   value 
        return self.conf.get("data_file_path", "dataname")

4、jsonフォーマットデータのkeyのすべての値を見つけます.
from jsonpath_rw import jsonpath, parse  #  Python Json     jsonpath-rw

class findValue:
    def __init__(self, data, data_from):
        #data     json     ,  “male”,    json      key “male”  ,  “student[*].male”    student    key “male”  
        #data_from    json  
        self.find_key = '$..%s' % (data)
        self.fromContent = data_from

    def theValue(self):  #     json    
        jsonpath_expr = parse(self.find_key)
        value_content = []
        for match in jsonpath_expr.find(self.fromContent):
            value_content.append(match.value)
        return value_content

check={
    "findkey":"1",
    "truevalue":{
        "a":1,
        "findkey":"1"
    }
}

print("  json   findkey     :",findValue("findkey", check).theValue())
print("  json   truevalue   findkey     :",findValue("truevalue.findkey", check).theValue())


出力:jsonデータ全体のfindkeyのすべての値は:[‘1’,‘1’]jsonデータ全体のtruevalueの下のfindkeyのすべての値は:[‘1’]