我想做的是:
csv数据:
HostXYZ1;Device IP;Interface name;Generic Server
HostXYZ2_very long hostname;Device IP;Interface name;Generic Server
HostXYZ3;Device IP;Very long interface name;Generic Server
脚本的主要部分:
input = sys.argv[1]
cprint(' Hostname | IP-Address | Interface | Device Type ', 'white', 'on_grey')
cprint('-'*128, 'white', 'on_grey')
with open('inventory.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=';', quotechar='|')
for row in reader:
if (input.lower() in row[0].lower()) or (input in row[1].lower()) or (input.lower() in row[2].lower()):
if len(row[0]) <= 13:
if len(row[1]) <= 13:
print(" " + row[0] + "\t -- " + row[1] + "\t -- " + row[2] + "\t --\t " + row[3])
elif len(row[1]) == 14:
print(" " + row[0] + "\t -- " + row[1] + " -- " + row[2] + "\t --\t " + row[3])
elif len(row[1]) == 15:
print(" " + row[0] + "\t -- " + row[1] + " -- " + row[2] + "\t --\t " + row[3])
else:
if len(row[1]) <= 13:
print(" " + row[0] + " -- " + row[1] + "\t -- " + row[2] + "\t --\t " + row[3])
elif len(row[1]) == 14:
print(" " + row[0] + " -- " + row[1] + " -- " + row[2] + "\t --\t " + row[3])
elif len(row[1]) == 15:
print(" " + row[0] + " -- " + row[1] + " -- " + row[2] + "\t --\t " + row[3])
我的主要问题是任何一列中的数据长度都可能变化,我无法找到一种方法来很好地打印结果,仅通过基于字符串长度的if语句进行堆叠即可。不可扩展...
我希望看到的输出:
Hostname | IP-Address | Interface | Device Type
--------------------------------------------------------------------------------------------------------------------------------
HostXYZ1 --- Device IP --- Interface name --- Generic Server
HostXYZ2_very long hostname --- Device IP --- Interface name --- Generic Server
HostXYZ3 --- Device IP --- Very long interface name --- Generic Server
有没有一种方法可以使用更Python化的方式来实现,在这里我所拥有的数据的长度无关紧要;仍然可以很好地将其打印出来并进行标签打印?
***更新: “如何用Python漂亮地打印CSV文件”并不是答案,因为它不是最好的pythonic方法。为此,您需要在自己的脚本中添加一个全新的脚本。