以下是一个示例代码,可以用于保存和加载数值和颜色到txt和xml文件中。
保存至txt文件:
def save_to_txt(values, colors, filename):
with open(filename, 'w') as file:
for value, color in zip(values, colors):
line = f"{value},{color}\n"
file.write(line)
print(f"保存成功:{filename}")
# 调用示例
values = [1, 2, 3, 4, 5]
colors = ['red', 'green', 'blue', 'yellow', 'purple']
save_to_txt(values, colors, 'data.txt')
加载txt文件:
def load_from_txt(filename):
values = []
colors = []
with open(filename, 'r') as file:
for line in file:
value, color = line.strip().split(',')
values.append(int(value))
colors.append(color)
return values, colors
# 调用示例
loaded_values, loaded_colors = load_from_txt('data.txt')
print(loaded_values)
print(loaded_colors)
保存至xml文件:
import xml.etree.ElementTree as ET
def save_to_xml(values, colors, filename):
root = ET.Element("data")
for value, color in zip(values, colors):
item = ET.SubElement(root, "item")
value_elem = ET.SubElement(item, "value")
value_elem.text = str(value)
color_elem = ET.SubElement(item, "color")
color_elem.text = color
tree = ET.ElementTree(root)
tree.write(filename)
print(f"保存成功:{filename}")
# 调用示例
values = [1, 2, 3, 4, 5]
colors = ['red', 'green', 'blue', 'yellow', 'purple']
save_to_xml(values, colors, 'data.xml')
加载xml文件:
def load_from_xml(filename):
values = []
colors = []
tree = ET.parse(filename)
root = tree.getroot()
for item in root.findall("item"):
value = int(item.find("value").text)
color = item.find("color").text
values.append(value)
colors.append(color)
return values, colors
# 调用示例
loaded_values, loaded_colors = load_from_xml('data.xml')
print(loaded_values)
print(loaded_colors)
请注意,以上代码仅为示例,实际使用时可能需要根据具体需求进行调整。
下一篇:保存/加载透视表配置