pandas實(shí)現(xiàn)將excel導(dǎo)出到y(tǒng)aml文件中
本文介紹了一個(gè)將Excel文件轉(zhuǎn)換為YAML格式的工具函數(shù)。該工具需要安裝pandas和pyyaml庫(kù),主要功能包括:讀取Excel表格數(shù)據(jù),處理空值和日期格式,并將結(jié)構(gòu)化數(shù)據(jù)輸出為YAML文件。
核心函數(shù)excel_to_yaml()接收Excel路徑、輸出YAML路徑和可選表名參數(shù),通過(guò)pandas讀取數(shù)據(jù)后轉(zhuǎn)換為字典列表,最后使用yaml.dump()寫(xiě)入文件。該工具可方便地將表格數(shù)據(jù)轉(zhuǎn)換為更適合配置使用的YAML格式。
首先需要安裝依賴:
pip install pandas pip install pyyaml
工具函數(shù)如下:
import pandas as pd
import yaml
def excel_to_yaml(excel_path, output_yaml_path, excel_sheet_name=0):
"""
將Excel文件轉(zhuǎn)換為YAML文件
:param excel_path: Excel文件路徑
:param output_yaml_path: 輸出YAML文件路徑
:param excel_sheet_name: Excel文件中的表名,默認(rèn)為0(第一個(gè)表)
"""
df = pd.read_excel(excel_path, sheet_name=excel_sheet_name)
data_list = df.to_dict('records')
for record in data_list:
for key, value in record.items():
if pd.isna(value): # 處理空值
record[key] = None
elif hasattr(value, 'strftime'): # 處理日期時(shí)間對(duì)象
record[key] = value.strftime('%Y-%m-%d')
with open(output_yaml_path, 'w', encoding='utf-8') as yaml_file:
yaml.dump(data_list, yaml_file, allow_unicode=True, sort_keys=False)
def main():
excel_path = "指數(shù)列表.xlsx"
output_yaml_path = "out_yaml.yaml"
excel_to_yaml(excel_path, output_yaml_path)
if __name__ == '__main__':
main()
方法補(bǔ)充:
1.Python讀取excel內(nèi)容寫(xiě)入yaml文件
使用Python將Excel文件內(nèi)容寫(xiě)入YAML文件的過(guò)程包括以下幾個(gè)步驟:
- 使用
openpyxl模塊讀取Excel文件; - 將Excel表格數(shù)據(jù)轉(zhuǎn)換成Python對(duì)象;
- 將Python對(duì)象轉(zhuǎn)換成YAML字符串;
- 將YAML字符串寫(xiě)入YAML文件。
完整代碼
import openpyxl
import yaml
xlsx_name = "data.xlsx"
# 打開(kāi)Excel文件
wb = openpyxl.load_workbook(xlsx_name)
sheet = wb.active
# 讀取Excel表格數(shù)據(jù)并存儲(chǔ)為Python對(duì)象
data = {'data': []}
for row in sheet.iter_rows(min_row=2, values_only=True):
item = {'name': row[0], 'age': row[1], 'email': row[2]}
data['data'].append(item)
for i in data['data']:
print(i)
# 將Python對(duì)象轉(zhuǎn)換成YAML字符串
yaml_data = yaml.dump(data)
# 將YAML字符串寫(xiě)入YAML文件
with open('data.yaml', 'w') as file:
file.write(yaml_data)
# 讀取yaml文件內(nèi)容
with open('data.yaml', 'r') as file:
dataR = yaml.load(file, Loader=yaml.FullLoader)
print(dataR)
'''
{'name': 's1', 'age': 22, 'email': 's1@xcel.com'}
{'name': 's2', 'age': 23, 'email': 's3@xcel.com'}
{'name': '宋', 'age': 24, 'email': 's4@xcel.com'}
{'data': [{'age': 22, 'email': 's1@xcel.com', 'name': 's1'}, {'age': 23, 'email': 's3@xcel.com', 'name': 's2'}, {'age': 24, 'email': 's4@xcel.com', 'name': '宋'}]}
'''2.Python腳本實(shí)現(xiàn)將excel 文件中的數(shù)據(jù)導(dǎo)入yaml文件
這是一個(gè)Python腳本,用于將Excel文件轉(zhuǎn)換為YAML格式。腳本讀取Excel工作簿中的數(shù)據(jù),創(chuàng)建一個(gè)有序字典結(jié)構(gòu),并填充測(cè)試用例的相關(guān)信息,如類型、名稱、描述、路徑等。最終,它將這個(gè)字典寫(xiě)入YAML文件,實(shí)現(xiàn)了測(cè)試用例的自動(dòng)化轉(zhuǎn)換。
import yaml
import os
from collections import OrderedDict
import openpyxl
class TestCases_protocol:
"""This script is to convert excel file to yaml file."""
def __init__(self,file_name,yaml_name):
self.file_name = file_name
self.yaml_name = yaml_name
self.final_dict = OrderedDict()
self.new_pltform_dic = OrderedDict()
def create_dict(self):
wb = openpyxl.load_workbook(self.file_name)
sheet_names = wb.sheetnames
count_cases=[]
for sheet_name in sheet_names:
print(sheet_name)
ws = wb[sheet_name]
max_row = ws.max_row
count_cases.append(max_row-2)
for n_row in range(3,max_row+1):
script_type = ws.cell(row=n_row, column=1).value
script_name = ws.cell(row=n_row, column=2).value
Description = ws.cell(row=n_row, column=3).value
script_path = ws.cell(row=n_row, column=4).value
if not script_type:
continue
else:
self.new_pltform_dic[script_name] = OrderedDict()
self.new_pltform_dic[script_name].update({
"type":script_type,
"loop":'1',
"duration":'60',
"description":Description,
"script_path":script_path,
"parameters": "default"
})
# for k,v in new_pltform_dic.items():
# print(k,':',v)
with open(self.yaml_name, 'w') as f:
yaml.dump(self.new_pltform_dic, f)
print(sum(count_cases))
if __name__=='__main__':
case1 = TestCases_protocol('Test.xlsx','new.yaml')
case1.create_dict()到此這篇關(guān)于pandas實(shí)現(xiàn)將excel導(dǎo)出到y(tǒng)aml文件中的文章就介紹到這了,更多相關(guān)pandas excel導(dǎo)出到y(tǒng)aml內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python+OpenCV實(shí)現(xiàn)圖片及視頻中選定區(qū)域顏色識(shí)別
這篇文章主要為大家詳細(xì)介紹了如何利用Python+OpenCV實(shí)現(xiàn)圖片及視頻中選定區(qū)域顏色識(shí)別功能,文中的示例代碼講解詳細(xì),感興趣的可以了解一下2022-07-07
TensorFlow可視化工具TensorBoard默認(rèn)圖與自定義圖
這篇文章主要介紹了TensorFlow可視化工具TensorBoard默認(rèn)圖與自定義圖的使用操作示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10
Python實(shí)現(xiàn)的多線程端口掃描工具分享
這篇文章主要介紹了Python實(shí)現(xiàn)的多線程端口掃描工具分享,工具實(shí)現(xiàn)了掃單IP和掃IP段功能,本文給出運(yùn)行效果和實(shí)現(xiàn)源碼,需要的朋友可以參考下2015-01-01
Python技巧之變長(zhǎng)和定長(zhǎng)序列拆分
這篇文章主要給大家分享的是Python技巧之變長(zhǎng)和定長(zhǎng)序列拆分,Python中的任何序列(可迭代的對(duì)象)都可以通過(guò)賦值操作進(jìn)行拆分,包括但不限于元組、列表、字符串、文件、迭代器、生成器等。想了解更多詳細(xì)的小伙伴請(qǐng)參考下面文章內(nèi)容2021-12-12
Python datetime 格式化 明天,昨天實(shí)例
這篇文章主要介紹了Python datetime 格式化 明天,昨天實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03

