简体   繁体   English

在打印语句正确时将输出写入文件时出现问题

[英]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. 我的打印语句的输出输出正确的数据行,但是输出文件仅包含3条if语句的最后几行。 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()

You need to indent the line 您需要缩进线

f.write(line1 + line2 + line3)

to the same level as the if statements before. 到与if语句相同的级别。 Currently, it's outside the for loop and is therefore executed only after that loop has ended. 当前,它在for循环之外,因此仅在该循环结束后才执行。

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. 正如乔恩克莱门特已经正确地指出,你需要考虑应该发生什么,如果不是所有的三个if都满足的条件-在这种情况下, lineN变量可以是未定义或仍与上一次迭代的值来定义。 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. 实际上, 不可能同时满足所有三个条件,因此您在第一次迭代中将始终遇到NameError

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. 只有您可以决定在for循环开始时将它们设置为默认值还是执行其他操作是否有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM