首页 > 解决方案 > 在 Python 中将 Excel 转换为 Yaml 语法

问题描述

我想将这种形式的数据转换为 YAML 语法(最好不使用 pandas 或需要安装新库)

excel中的示例数据:

users | name | uid | shell

user1 | nino | 8759 | /bin/ksh

user2 | vivo | 9650 | /bin/sh

所需的输出格式: YAML 语法输出

标签: pythonjsonexcelpandasyaml

解决方案


您可以使用文件操作来完成。既然你热衷于 * " 最好不用pandas或者不需要安装新库

假设:“|” 符号用于指示列,不是分隔符或分隔符

步骤1

Save the excel file as CSV

然后运行代码

代码

# STEP 1  : Save your excel file as CSV

ctr = 0
excel_filename = "Book1.csv"
yaml_filename = excel_filename.replace('csv', 'yaml')
users = {}

with open(excel_filename, "r") as excel_csv:
    for line in excel_csv:
        if ctr == 0:
            ctr+=1  # Skip the coumn header
        else:
            # save the csv as a dictionary
            user,name,uid,shell = line.replace(' ','').strip().split(',')
            users[user] = {'name': name, 'uid': uid, 'shell': shell}



with open(yaml_filename, "w+") as yf :
    yf.write("users: \n")
    for u in users:
        yf.write(f"  {u} : \n")
        for k,v in users[u].items():
            yf.write(f"    {k} : {v}\n")

输出

users: 
  user1 : 
    name : nino
    uid : 8759
    shell : /bin/ksh
  user2 : 
    name : vivo
    uid : 9650
    shell : /bin/sh

推荐阅读