【发布时间】:2015-02-02 08:27:49
【问题描述】:
目标是运行模块“printReport”,它读取文件“arrivals_14_16.txt”并将文件的前四行写入文件“text.txt”。但它只写了第一行。
在模块“readInput.py”的函数“headerArrivalsFile”中,如果我离开“打印行”,函数最后打印前四行,但如果我离开“返回行”,最后它只返回第一行。
但模块“printReport.py”中的函数“operationReport”仅在我将函数“headerArrivalsFile”最后带有“return”时才有效,如果我离开“print”模块“printReport.py”停止工作.
模块:readInput.py
def headerArrivalsFile(file_name):
"""
"""
inFile = open(file_name, "r")
for line in inFile:
if "Arrivals:" in line:
break
return line, ## print line, ## (How do I put this work with -> return line,)
inFile.close()
模块:printReport.py
from readInput import headerArrivalsFile
def operationReport(inputFile, outputFile):
""""
""""
inFile = open(inputFile, "r")
outFile = open(outputFile, "w")
for line in headerArrivalsFile(inputFile):
outFile.write(line)
outFile.close()
inFile.close()
inFile:arrivals_14_16.txt
Airport: Neverland
Number of belts: 3
Day: 06:11:2014
Period: from 14:00 to 16:00
Arrivals:
KLM75, Amsterdam, 14:35, 60, 50
AF111, Paris, 14:20, 50, 64
LH333, Frankfurt, 14:10, 112, 203
KLM71, Madrid, 14:55, 120, 100
TAP103, Salvador, 15:20, 174, 210
LH123, Berlin, 15:10, 115, 210
outFile: test.txt(我想得到的)
Airport: Neverland
Number of belts: 3
Day: 06:11:2014
Period: from 14:00 to 16:00
outFile: test.txt(我得到的)
Airport: Neverland
【问题讨论】:
-
在函数中,将 'return' 替换为 'yield' 使其成为生成器。