我想将这种形式的数据转换为YAML语法(最好不使用panda或不需要安装新库(
excel中的样本数据:
users | name | uid | shell
user1 | nino | 8759 | /bin/ksh
user2 | vivo | 9650 | /bin/sh
所需的输出格式:YAML语法输出
您可以使用文件操作来完成。既然你热衷于*"最好不使用panda或需要安装新库
假设:|"符号用于指示列,而不是分隔符或分隔符
步骤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
您可以这样做,在您的情况下,您只需要执行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