AlliDeacon
AlliDeacon

Reputation: 1495

python create and append txt file using loops and variables

I have created variables that I need to drop into txt files. I am not having any success. My program will create the header information, but stops writing to the file after that. The top loop is my "Order Header" and the machines loop is my "Order Detail". I've tried debugging, and looking at it from every angle. I can't figure out what I'm doing wrong. The program is writing all of the text files and appending for the XHORNO and XHCSNO. As far as troubleshooting, I have tried print statements (print "header" print "detail", and print "machine" ) to verify that the code was hitting each loop as expected. That effort resulted in the correct output. However it won't write the detail loops variables to file.

for k, v in atlantic_billing.iteritems():
    # print "header"
    #CREATE XHORNO
    XHORNO = str(digits + counter)
    print XHORNO
    with open(XHORNO + ".txt", 'w') as order:
        XHCSNO = k
        machines = v
        #create order header information
        order.write(XHORNO+"\n")
        order.write(XHCSNO+"\n")
        line = 1
        counter = counter + 1
        for machine in machines :
            try:
                XDORNO = XHORNO
                XDORSQ = line
                line = line + 1
                XDITD1 = ranpak_dict[machine]['MODEL']
                XDITD2 = ranpak_dict[machine]['SN']
                XDCAVC = ranpak_dict[machine]['TOTAL']
                order.write(XDORDQ + "\n")
                order.write(XDITD1 + "\n")
                success.append(machine)
                lines = lines + 1

            except :
                issues.append(machine)
                problems = problems + 1

Upvotes: 0

Views: 697

Answers (1)

glibdud
glibdud

Reputation: 7840

Best guess with the given information... each loop is getting down to:

lines = lines + 1

And then throwing a NameError because lines is undefined (you called it line before). Since your except clause is catching all exceptions, the program quietly adds that entry to problems and moves on.

This is a good example of why you should try to be as specific as possible about what errors you catch in your except clauses.

Edit: ...but I suppose it should still have written the lines to the file at that point? So... possibly still more information needed. But definitely narrow down your except to make it easier to troubleshoot.

Upvotes: 3

Related Questions