I am new to Python. With the following code I am creating a csv file:
import csv
from itertools import zip_longest
import random
total = int(input("Enter the total number of external products: "))
devices =[]
ipadd = []
versions=[]
commas=[]
dict1 = {}
device_tags = []
taglist = ["Critical","Test","Prod","Dev","EOL","Internet"]
products = []
for i in range(total):
ext = "Mss" str(i)
products.append(ext)
for j in range(0,len(products)):
tag = random.choice(taglist)
device_tags.append(tag)
for version in range(0,len(products)):
v = "Version1.1"
c = " "
versions.append(v)
commas.append(c)
heads=["rcp_product_alias(*)","version","device_name(*)","ipaddress(*)","device_cutoff_date (yyyy-mm-dd)","new_version","schedule","device_tags(semi-colon delimited)"]
for i in range(len(products)):
devicename = 'hostname' str(i)
devices.append(devicename)
ip = '100.100.100.' str(i)
ipadd.append(ip)
heads=["rcp_product_alias(*)","version","device_name(*)","ipaddress(*)","device_cutoff_date (yyyy-mm-dd)","new_version","schedule","device_tags(semi-colon delimited)"]
with open('SampleExternalInventroy-MSS.csv', 'w',newline='') as f:
w=csv.writer(f)
w.writerow(heads)
for a,b,c,d,e,f,g,h in zip_longest(products,versions,devices,ipadd,commas,commas,commas,device_tags):
w.writerow([a,b,c,d,e,f,g,h])
The code is working fine, but it looks very inefficient to me. What could be improved?
The output should be:
rcp_product_alias(*),version,device_name(*),ipaddress(*),device_cutoff_date (yyyy-mm-dd),new_version,schedule,device_tags(semi-colon delimited)
Mss0,Version1.1,hostname0,100.100.100.0, , , ,Prod
Mss1,Version1.1,hostname1,100.100.100.1, , , ,EOL
Mss2,Version1.1,hostname2,100.100.100.2, , , ,Dev
Mss3,Version1.1,hostname3,100.100.100.3, , , ,Critical
Mss4,Version1.1,hostname4,100.100.100.4, , , ,EOL
Mss5,Version1.1,hostname5,100.100.100.5, , , ,Internet
Mss6,Version1.1,hostname6,100.100.100.6, , , ,Critical
Mss7,Version1.1,hostname7,100.100.100.7, , , ,Critical
CodePudding user response:
You could do something like this
import csv
from random import choice
total = int(input("Enter the total number of external products: "))
taglist = ["Critical", "Test", "Prod", "Dev", "EOL", "Internet"]
header = [
"rcp_product_alias(*)", "version", "device_name(*)", "ipaddress(*)",
"device_cutoff_date (yyyy-mm-dd)", "new_version", "schedule",
"device_tags(semi-colon delimited)"
]
with open("SampleExternalInventroy-MSS.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(header)
writer.writerows(
[f"Mss{n}", "Version1.1", f"hostname{n}", f"100.100.100.{n}",
" ", " ", " ", choice(taglist)]
for n in range(total)
)
to make it a bit more compact and readable.