如何使用导入从文件写入另一个文件?

时间:2014-12-04 12:41:01

标签: python string file import

目标是运行模块“printReport”,它读取文件“arrivals_14_16.txt”并将文件中的前四行写入文件“text.txt”。但它只写第一行。

在模块“readInput.py”的函数“headerArrivalsFile”中,如果我离开“print line”,最后该函数会打印出前四行,但如果我离开“return line”,到底它只返回第一行。

但是模块“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

2 个答案:

答案 0 :(得分:0)

问题在于headerArrivalsFile()的作用与调用代码期望它做的不匹配。这一行:

for line in headersArrivalFile(inputFile):

告诉python该函数将返回它将迭代的东西(字符串,序列,映射或生成器)。你的功能(完全如此处所示)

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

返回None,所以我很惊讶你看到任何输出。当你找到抵达线时,返回前的'休息'会让你直接收盘。如果找不到它,则会退出循环并关闭文件。两条路线都没有返回任何值。

所以需要先解决。您不需要任何循环,只需:

def headerArrivalsFile(file_name):
    with open(file_name,"r") as infile:
        # Read the entire file, stripping *only* newlines
        contents = [l.rstrip('\n') for l in infile]

    if "Arrivals:" in contents:
        return infile[:infile.index("Arrivals:")]

    return contents

请注意使用'with'在阅读后自动关闭文件。

现在到调用函数

def operationReport(inputFile, outputFile):
    """"
    """"
    inFile = open(inputFile, "r")
    outFile = open(outputFile, "w")
    for line in headerArrivalsFile(inputFile):
        outFile.write(line)
    outFile.close()
    inFile.close()

你在headerArrivalsFile()中打开文件,所以在这里再打开它没有意义。此外,再次使用'with'可确保文件即使在异常情况下也会关闭。

def operationReport(inputFile, outputFile):
    with open(outputFile, "w") as outFile:
        for line in headerArrivalsFile(inputFile):
            outFile.write(line+'\n')

另请注意,我已添加了已删除的换行符

答案 1 :(得分:0)

'返回'停止执行某个功能。无论代码在哪里,它都会停止在'返回'或者当没有更多的代码要执行时,以先到者为准。

将结果放入列表中,然后返回该列表或使用yield。