在Python中保存文件的格式取决于所保存的文件类型。以下是如果保存不同类型的文件的格式示例:
- 文本文件
text_file = open(“filename.txt”, “w”)
text_file.write(“写入文本文件的内容”)
text_file.close()
- CSV文件
import csv
csv_file = open(“filename.csv”, “w”, newline=“”)
csv_writer = csv.writer(csv_file)
csv_writer.writerow([“列1”, “列2”, “列3”])
csv_writer.writerow([“行1数据1”, “行1数据2”, “行1数据3”])
csv_file.close()
- JSON文件
import json
data = {“key1”: “value1”, “key2”: “value2”}
json_file = open(“filename.json”, “w”)
json.dump(data, json_file)
json_file.close()
- XML文件
import xml.etree.ElementTree as ET
root = ET.Element(“根”)
child1 = ET.SubElement(root, “子节点1”)
child2 = ET.SubElement(root, “子节点2”)
child1.text = “子节点1的内容”
child2.text = “子节点2的内容”
xml_file = open(“filename.xml”, “w”)
xml_file.write(ET.tostring(root, encoding=“unicode”))
xml_file.close()