我正在尝试写一个"订单文件"带有标题和细节线。我成功获取了要写入文件的订单标题,但只有一个详细信息行似乎写入文件。
for k, v in atlantic_billing.iteritems():
XHORNO = str(digits + counter)
XHCSNO = k
print XHCSNO
machines = v
line = 1
counter = counter + 1
header_written = False
try :
for machine in machines :
XDORNO = XHORNO
XDORSQ = line
line = line + 1
XDITD1 = ranpak_dict[machine]['MODEL']
XDITD2 = ranpak_dict[machine]['SN']
XDCAVC = ranpak_dict[machine]['TOTAL']
print XDORSQ, XDITD1, XDITD2, XDCAVC
if XDCAVC > 0 :
if header_written == False :
with open(XHORNO + ".txt", 'w') as order:
order.write("H01, " + XHORNO + ", " + XHCSNO + "\n")
order.write("D01," + str(XDORSQ) + ", " + ' EQPRANUSER, ' + XDITD1 + ", " + XDITD2 + ", " + XDCAVC + "\n")
else :
order.write("D01," + str(XDORSQ) + ", " + ' EQPRANUSER, ' + XDITD1 + ", " + XDITD2 + ", " + XDCAVC + "\n")
success.append(machine)
header_written = True
except KeyError, e:
issues.append(machine)
答案 0 :(得分:2)
打开文件时,您应该使用模式"A"
否则文件将在每个循环中被覆盖(一次又一次):
with open(XHORNO + ".txt", 'a') as order:
...
请参阅https://docs.python.org/3/library/functions.html#open
另一个选择是将with
块放在for块上。
答案 1 :(得分:1)
您只需要打开一次文件而不是在循环中
for k, v in atlantic_billing.iteritems():
XHORNO = str(digits + counter)
with open(XHORNO + ".txt", 'w') as order: # <--- here you go
XHCSNO = k
print XHCSNO
machines = v
line = 1
counter = counter + 1
header_written = False
try :
for machine in machines :
XDORNO = XHORNO
XDORSQ = line
line = line + 1
XDITD1 = ranpak_dict[machine]['MODEL']
XDITD2 = ranpak_dict[machine]['SN']
XDCAVC = ranpak_dict[machine]['TOTAL']
print XDORSQ, XDITD1, XDITD2, XDCAVC
if XDCAVC > 0 :
if header_written == False :
order.write("H01, " + XHORNO + ", " + XHCSNO + "\n")
order.write("D01," + str(XDORSQ) + ", " + ' EQPRANUSER, ' + XDITD1 + ", " + XDITD2 + ", " + XDCAVC + "\n")
else :
order.write("D01," + str(XDORSQ) + ", " + ' EQPRANUSER, ' + XDITD1 + ", " + XDITD2 + ", " + XDCAVC + "\n")
success.append(machine)
header_written = True
except KeyError, e:
issues.append(machine)
答案 2 :(得分:0)
试试这个:
for k, v in atlantic_billing.iteritems():
XHORNO = str(digits + counter)
XHCSNO = k
print XHCSNO
machines = v
line = 1
counter = counter + 1
header_written = False
try :
for machine in machines :
XDORNO = XHORNO
XDORSQ = line
line = line + 1
XDITD1 = ranpak_dict[machine]['MODEL']
XDITD2 = ranpak_dict[machine]['SN']
XDCAVC = ranpak_dict[machine]['TOTAL']
print XDORSQ, XDITD1, XDITD2, XDCAVC
if XDCAVC > 0 :
with open(XHORNO + ".txt", 'a') as order:
if header_written == False :
order.write("H01, " + XHORNO + ", " + XHCSNO + "\n")
order.write("D01," + str(XDORSQ) + ", " + ' EQPRANUSER, ' + XDITD1 + ", " + XDITD2 + ", " + XDCAVC + "\n")
header_written = True
else :
order.write("D01," + str(XDORSQ) + ", " + ' EQPRANUSER, ' + XDITD1 + ", " + XDITD2 + ", " + XDCAVC + "\n")
success.append(machine)
except KeyError, e:
issues.append(machine)