gpt4 book ai didi

Python - 一次写入 header - 循环无法正常工作

转载 作者:行者123 更新时间:2023-11-30 23:00:27 25 4
gpt4 key购买 nike

我正在尝试编写一个带有标题行和详细信息行的“订单文件”。我成功地将订单 header 写入文件,但似乎只有一个详细信息行被写入文件。

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)

最佳答案

打开文件时,应使用模式“A”,否则文件将在每次循环时被覆盖(一次又一次):

 with open(XHORNO + ".txt", 'a') as order:
...

参见https://docs.python.org/3/library/functions.html#open

另一种选择是使用 with block 而不是 for block 。

关于Python - 一次写入 header - 循环无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35272781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com