gpt4 book ai didi

python - 将输出保存(打印)为 xml 文件不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 11:13:42 25 4
gpt4 key购买 nike

我写了一个小程序,用一个函数逐行读取一个 csv 文件。然后将输出结构保存在一个变量中。然后我想打开一个 xml 文件并将我的输出与变量一起传递。不知何故,当我打开保存的文件时,并没有保存整个输出。

import pandas as pd
df = pd.read_csv('mytests.csv', sep=',')

def csv_to_xml(row):
return """ <Test Testname="%s">
<Health_Feat>%s</Health_Feat>
<Result>%s</Result>
</Test>""" % (row.test_name, row.health_feat, row.result)
for index, row in df.iterrows():
xml_1 = (csv_to_xml(row))
print(xml_1)

f = open("new_xml_1.xml","w+")
f.write(xml_1)
f.close()

当我打印出 xml_1 时得到这个输出

  <Test Testname="test_1">
<Health_Feat>20</Health_Feat>
<Result>1</Result>
</Test>
<Test Testname="test_2">
<Health_Feat>23</Health_Feat>
<Result>1</Result>
</Test>
<Test Testname="test_3">
<Health_Feat>24</Health_Feat>
<Result>0</Result>
</Test>
<Test Testname="test_3">
<Health_Feat>30</Health_Feat>
<Result>1</Result>
</Test>
<Test Testname="test_4">
<Health_Feat>12</Health_Feat>
<Result>1</Result>
</Test>
<Test Testname="test_5">
<Health_Feat>45</Health_Feat>
<Result>0</Result>
</Test>
<Test Testname="test_6">
<Health_Feat>34</Health_Feat>
<Result>1</Result>
</Test>
<Test Testname="test_7">
<Health_Feat>78</Health_Feat>
<Result>1</Result>
</Test>
<Test Testname="test_8">
<Health_Feat>23</Health_Feat>
<Result>1</Result>
</Test>
<Test Testname="test_9">
<Health_Feat>12</Health_Feat>
<Result>1</Result>
</Test>
<Test Testname="test_10">
<Health_Feat>12</Health_Feat>
<Result>2</Result>
</Test>

但是当我打开“new_xml_1.xml”文件时,我只得到

  <Test Testname="test_10">
<Health_Feat>12</Health_Feat>
<Result>2</Result>
</Test>

我真的不知道为什么我的程序表现如此奇怪。我认为它与循环到 csv 的行有关

感谢您的帮助。我是 Python 和编程的新手,所以我想获得一些经验。

最佳答案

它只保存最后一个输出,因为你在 for 循环之后保存外部变量 xml_1,它只有最后一个输出。在循环之前打开文件,并在循环内写入,就像在循环内打印一样。

f = open("new_xml_1.xml","w+")

for index, row in df.iterrows():
xml_1 = (csv_to_xml(row))
print(xml_1)
f.write(xml_1)

f.close()

关于python - 将输出保存(打印)为 xml 文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57552041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com