下面是我的python脚本的一部分,它在Linux系统和日常自动化系统中读取数据。在邮件正文和邮件中打印发送。我的输入文件每天都在变化,如果输入文件包含所有字符串(或)numarical值,它将完美地运行。
如果输入文件在任何行中都有空字符串/值,则会抛出IndexError并停止打印数据。
f = open('INPUTfile')
lines = f.readlines()
count=len(lines)
f.close()
body1="""
"""
z=0
while (z<count):
test = lines[z]
hello = test.split(',')
a = hello[0:1]
a1 = a[0]
b = hello[1:2]
b1 = b[0]
c = hello[2:3]
c1 = c[0]
d = hello[3:4]
d1 = d[0]
e = hello[4:5]
e1 = e[0]
f = hello[5:6]
f1 = f[0]
g = hello[6:7]
g1 = g[0]
h = hello[7:8]
h1 = h[0]
i = hello[8:9]
i1 = i[0]
j = hello[9:10]
j1 = j[0]
k = hello[10:11]
k1 = k[0]
l = hello[11:12]
l1 = l[0]
m = hello[12:13]
m1 = m[0]
d1 = float(d[0])
g1 = float(g[0])
j1 = float(j[0])
m1 = float(m[0])
if all([d1 < 99.00, j1 < 99.00]):
body1 = body1 + '<tr><td style="font-family:Calibri;"><b>' + a1 + '</b></td><td style="font-family:Calibri;">' + b1 + '</td></td><td style="font-family:Calibri;">' + c1 + '</td></td><td style="font-family:Calibri;color:red">' + str(round(d1,2)) + '</td></td><td style="font-family:Calibri;">' + e1 + '</td><td style="font-family:Calibri;">' + f1 + '</td></td><td style="font-family:Calibri;color:red">' + str(round(g1,2)) + '</td><td style="font-family:Calibri;">' + h1 + '</td><td style="font-family:Calibri;">' + i1 + '</td><td style="font-family:Calibri;">' + str(round(j1,2)) + '</td><td style="font-family:Calibri;">' + k1 + '</td><td style="font-family:Calibri;">' + l1 + '</td><td style="font-family:Calibri;">' + str(round(m1,2)) + '</td></tr>'
z=z+1
我的inputfile
:
APPU1,2004423,2004417,99.9997,2847,2847,100,7600,7599,99.9846,1248,1248,99.9999
APPU2,,,
APPU3,2004333,2004329,99.9998,2848,2848,100,7593,7592,99.9842,1248,1247,99.9999
APPU4,2004020,2004016,99.9998,2849,2847,100,7596,7595,99.9853,1248,1247,99.9999
请建议打印数据的解决方案,即使INPUT文件中的行包含空值。
答案 0 :(得分:0)
我不明白在这里使用while循环。
无论如何,你需要的是while循环开始时的if语句。
while (z<count):
test = lines[z]
hello = test.split(',')
if len(hello) < 14: # or whatever number of items required.
z+=1
continue
#rest of your code goes here
如果我是你,我会写这样的代码。
with open('INPUTfile') as f:
for i, line in enumerate(f):
hello = line.split(',')
#rest of the code.
答案 1 :(得分:0)
您可以在python中使用try except
块。
try:
<your logic here> or the code
except IndexError:
pass # If IndexError is encountered, pass the control to the loop and continue from the next line
使用此代码段并检查是否可以解决问题
for line in lines:
try:
test = line
hello = test.split(',')
a = hello[0:1]
a1 = a[0]
b = hello[1:2]
b1 = b[0]
c = hello[2:3]
c1 = c[0]
d = hello[3:4]
d1 = d[0]
e = hello[4:5]
e1 = e[0]
f = hello[5:6]
f1 = f[0]
g = hello[6:7]
g1 = g[0]
h = hello[7:8]
h1 = h[0]
i = hello[8:9]
i1 = i[0]
j = hello[9:10]
j1 = j[0]
k = hello[10:11]
k1 = k[0]
l = hello[11:12]
l1 = l[0]
m = hello[12:13]
m1 = m[0]
d1 = float(d[0])
g1 = float(g[0])
j1 = float(j[0])
m1 = float(m[0])
except IndexError:
pass