Amy Rose
Amy Rose

Reputation: 95

Problems writing output to file when print statement is fine

The output from my print statements outputs the correct lines of data, the output file however only contains the last lines for the 3 if statements. I have tried varying the identation but this seems to only affect the code negatively.

import sys
import tokenize

file = []

f = open('Database.txt') # Opening File

for line in f:
file.append(line) # Reading in File

f.close() # Closing File

f = open('output.txt', 'w')

for line in file: # Printing out File
#print line

    tokens = line.split() # splits lines along white-space (tokenise)
    #print tokens
    desired =  '{0:<5}'.format(tokens[0])
    #print desired
    lined = line.split('|') # lhs is original line       

    if 'Not present in Line' in line:
        line1 = desired + ':' + lined[1]
        #print line1

    if 'Not present in TV' in line:
        #print line
        line2 = desired + ' : ' + ' sticking ' + ' Returning ' + '\n'  
        #print line2

    if 'Not present in Line' not in line and 'Not present in TV' not in line:
        #print line
        line3 = desired + ':' + lined[1]
        #print line3

f.write(line1 + line2 + line3)

f.close()

Upvotes: 0

Views: 76

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

You need to indent the line

f.write(line1 + line2 + line3)

to the same level as the if statements before. Currently, it's outside the for loop and is therefore executed only after that loop has ended.

Also, you may want to add a newline character after each line:

f.write(line1 + line2 + line3 + "\n")

As Jon Clements has noted correctly, you need to think about what should happen if not all three if conditions are met - in that case, lineN variables may be undefined or may still be defined with the value from the previous iteration. In fact, it's impossible for all three conditions to be met at the same time, so you'll always encounter a NameError during the very first iteration.

Only you can decide if it makes sense to set them to a default value at the start of the for loop or to do something else.

Upvotes: 3

Related Questions