繁体   English   中英

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

[英]Problems writing output to file when print statement is fine

我的打印语句的输出输出正确的数据行,但是输出文件仅包含3条if语句的最后几行。 我尝试过更改标识,但这似乎只会对代码产生负面影响。

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()

您需要缩进线

f.write(line1 + line2 + line3)

到与if语句相同的级别。 当前,它在for循环之外,因此仅在该循环结束后才执行。

另外,您可能希望在每行之后添加换行符:

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

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

只有您可以决定在for循环开始时将它们设置为默认值还是执行其他操作是否有意义。

暂无
暂无

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

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