Python生成指定数量的随机XML文件
我的需求是随机生成18位数字的XML文件名,其中前12位数字是随机数,后6位是时间信息
其中XML中写入CSN的tag值,代码如下
import os
import random
import time
import xml.etree.ElementTree as ET
def generate_random_filename():
random_part = ''.join([str(random.randint(0, 9)) for _ in range(12)])
timestamp_part = str(int(time.time()))[-6:]
return f"{random_part}{timestamp_part}.xml"
def create_xml_file(filename):
root = ET.Element("root")
child = ET.SubElement(root, "CSN")
child.text = "234567"
tree = ET.ElementTree(root)
with open(filename, 'wb') as fh:
tree.write(fh)
def main():
os.makedirs("xml_files", exist_ok=True) # Create a directory for the XML files
for _ in range(40):
filename = generate_random_filename()
filepath = os.path.join("xml_files", filename)
create_xml_file(filepath)
print(f"Created: {filepath}")
if __name__ == "__main__":
main()
最后生成的xml文件如下图所示:
最后还是不得不感叹一下Python的语法是真的简单,库也很多很方便用