如何解决在Python中将Excel转换为Yaml语法
我想将这种形式的数据转换为YAML语法(最好不使用熊猫或需要安装新库)
在excel中采样数据:
users | name | uid | shell
user1 | nino | 8759 | /bin/ksh
user2 | vivo | 9650 | /bin/sh
所需的输出格式: YAML Syntax output
解决方法
您可以执行此操作,在您的情况下,您只需执行pd.read_excel
而不是pd.read_csv
:
df = pd.read_csv('test.csv',sep='|')
df['user_col'] = 'users'
data = df.groupby('user_col')[['users','name','uid','shell']].apply(lambda x: x.set_index('users').to_dict(orient='index')).to_dict()
with open('newtree.yaml',"w") as f:
yaml.dump(data,f)
Yaml文件如下:
users:
user1:
name: nino
shell: /bin/ksh
uid: 8759
user2:
name: vivo
shell: /bin/sh
uid: 9650
,
您可以使用文件操作来做到这一点。由于您热衷于* ”,因此最好不使用熊猫,也不需要安装新的库
假设:“ |”符号用于指示列,而不是定界符或分隔符
步骤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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。