我的打印語句的輸出輸出正確的數據行,但輸出文件僅包含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()
您還需要縮進第9行:'file.append(line)',否則它不在'for'循環中。 – moopet 2016-11-22 13:39:28