我正在嘗試使用標題和明細行編寫「訂單文件」。我成功地將訂單標題寫入文件,但只有一條細節行似乎寫入文件。Python - 寫入標題一次 - 循環無法正常工作
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)
我想你想做的事'開放(XHORNO + 「.TXT」 「w」)作爲順序:'在機器的開始之前''machine:'循環。另外,我會在'if header_written == False:'塊中放置'header_written = True'。 –
@DavidCullen如果我將'open(XHORNO +「txt」,「a」)'移動到'for machine in machine:'循環之前,它會寫入文件,然後我才能驗證任何行是可計費的? – AlliDeacon
它將創建該文件,但在調用'order.write'之前不會寫任何內容。這聽起來不像你想要的行爲。然而,在'if'語句中放置'open'(XHORNO +「.txt」,'w')作爲命令:'幾乎可以肯定不是你想要的行爲,因爲'order'在' if語句(在'else'語句之前)。也許你應該在行列表中收集每臺機器的數據,然後在'machine for machine:'循環中寫入行列表後,如果行列表的長度大於零。 –