python - 在 Python 中将 Excel 转换为 Yaml 语法
问题描述
我想将这种形式的数据转换为 YAML 语法(最好不使用 pandas 或需要安装新库)
excel中的示例数据:
users | name | uid | shell
user1 | nino | 8759 | /bin/ksh
user2 | vivo | 9650 | /bin/sh
所需的输出格式: YAML 语法输出
解决方案
您可以使用文件操作来完成。既然你热衷于 * " 最好不用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
推荐阅读
- c++ - 如何使用主要参数添加更多堆栈?
- php - PHP Decimal128 字符串格式化
- ios - 打印语句总是崩溃
- azure-devops - 如何从 Azure DevOps 在 Microsoft AppCenter 中运行 XCUITests
- javascript - 如何延迟请求数据?
- python - pandas 中的高效 STAR 选择
- python - “int”类型的参数是不可迭代的问题
- javascript - 使用 Google App Script 替换 Google Sheet 中的文本而不重新格式化值
- linux - 在 Spark 中运行多个作业
- java - 生成一个 jar 并将其用作另一个模块中的依赖项