auto_test_dev/commons/FileHandler.py

79 lines
2.6 KiB
Python

# -*- coding: utf-8 -*-
import os, xlrd, yaml
from openpyxl import load_workbook
class YamlHandler():
'''@Author:: Arthur Wu
@Date:: 2024/5/8
@Description::
'''
def read_yaml(self, YamlFilePath, encoding='utf-8'):
try:
with open(YamlFilePath, encoding=encoding) as f:
return yaml.load(f.read(), Loader=yaml.FullLoader)
except Exception as e:
print("ERROR: read yaml file error::".format(e))
return 'failed to read config file.'
def read_some_yamls(self, YamlFilePathsList, encoding='utf-8'):
try:
result = []
for YamlFilePath in YamlFilePathsList:
with open(YamlFilePath, encoding=encoding) as f:
data = yaml.load(f.read(), Loader=yaml.FullLoader)
result.append(data)
return result
except Exception as e:
print("ERROR: read some yaml files error::".format(e))
return 'failed to read config file.'
class ReadExcel(object):
'''@Author:: Arthur Wu
@Date:: 2024/5/8
@Description::
'''
def get_data(self, FilePath, SheetName="Sheet1"):
data = load_workbook(FilePath)
table = data[SheetName]
nrows = table.max_row
ncols = table.max_column
if nrows > 1:
test_data = []
for row in range(2, nrows + 1):
sub_data = {}
for colum in range(1, ncols + 1):
sub_data[table.cell(1, colum).value] = table.cell(row, colum).value
test_data.append(sub_data)
return test_data
class Txt():
'''@Author:: Arthur Wu
@Date:: 2024/5/8
@Description::
'''
def __init__(self):
rootpath = os.path.dirname(os.path.dirname(__file__))
self.record_files_path = os.path.join(rootpath, 'YiMao/ProcessData').replace("\\", "/")
def read_txt(self, FileName):
filepath = os.path.join(self.record_files_path, FileName)
AllLineValue = []
if os.path.exists(filepath):
with open(filepath, "r", encoding='utf-8') as file:
for lineval in file:
newlineval = lineval.strip()
AllLineValue.append(newlineval)
return AllLineValue
def append_write_txt(self, FileName, Message):
try:
filepath = os.path.join(self.record_files_path, FileName)
with open(filepath, "a", encoding='UTF-8') as f:
f.write(Message + '\n')
return True
except Exception as e:
print("Error: append_write_txt error::" + str(e))
return False