Python 3.x 如何将打开的文件作为变量传递给多个函数?

Python 3.x 如何将打开的文件作为变量传递给多个函数?,python-3.x,Python 3.x,我的目标是使用多个函数在日志中搜索字符串 我遇到了这样一个问题:只有在打开文件后调用的第一个函数才能检索文件的全部内容。所有其他函数都不会检索打开文件的任何内容 为了进行测试,我使用了一个包含以下文本的简单文件: aaa this is line 1 bbb this is line 2 ccc this is line 3 ddd this is line 4 eee this is line 5 fff this is line 6 ggg this is line 7 这是我的代码中存在

我的目标是使用多个函数在日志中搜索字符串

我遇到了这样一个问题:只有在打开文件后调用的第一个函数才能检索文件的全部内容。所有其他函数都不会检索打开文件的任何内容

为了进行测试,我使用了一个包含以下文本的简单文件:

aaa this is line 1
bbb this is line 2
ccc this is line 3
ddd this is line 4
eee this is line 5
fff this is line 6
ggg this is line 7
这是我的代码中存在问题的部分。

def main():
    with open('myinputfile.txt', 'r') as myfile:
        get_aaa(myfile)
        get_bbb(myfile)
        get_fff(myfile)
每个get_xxx函数只搜索一个字符串。get_aaa()搜索^aaa,get_bbb()搜索^bbb,get_fff()搜索^fff。如果找到字符串,函数将打印一些文本以及匹配行。如果未找到字符串,则打印“未找到”消息

运行脚本时,我收到以下输出:

Start Date:  aaa this is line 1
ITEM BBB: NOT FOUND
ITEM FFF: NOT FOUND
Start Time:  bbb this is line 2
ITEM AAA: NOT FOUND
ITEM FFF: NOT FOUND
当我修改main()并重新排序以在get_aaa()之前调用get_bbb()时,我收到以下输出:

Start Date:  aaa this is line 1
ITEM BBB: NOT FOUND
ITEM FFF: NOT FOUND
Start Time:  bbb this is line 2
ITEM AAA: NOT FOUND
ITEM FFF: NOT FOUND
基于此测试,我确信只有在打开文件后调用的第一个函数才能读取文件的全部内容。

对于其他测试,如果在调用每个函数之前打开文件,我会收到预期的输出。

def main():
    with open('myinputfile.txt', 'r') as myfile:
        get_aaa(myfile)
    with open('myinputfile.txt', 'r') as myfile:
        get_bbb(myfile)
    with open('myinputfile.txt', 'r') as myfile:
        get_fff(myfile)
        myfile.close(
结果达到了预期的产出

Start Date:  aaa this is line 1
Start Time:  bbb this is line 2
UserId :     fff this is line 6

关于如何一次打开文件并使用多种功能搜索文件内容的提示?

请先阅读您的文件,然后应用这些功能

def get_aaa(lines):
    for line in lines.split('\n'):
        if line.startswith('aaa'): return line 

def get_bbb(lines):
    for line in lines.split('\n'):
        if line.startswith('bbb'): return line 

def get_ccc(lines):
    for line in lines.split('\n'):
        if line.startswith('ccc'): return line 

def main():
    with open('test.txt', 'r') as myfile:
        lines = myfile.read()
        print(get_aaa(lines))
        print(get_bbb(lines))
        print(get_ccc(lines))

main()
结果是

aaa this is line 1
bbb this is line 2
ccc this is line 3
如何将打开的文件作为变量传递给多个函数

你做得对

至于这不起作用的原因:

def main():
    with open('myinputfile.txt', 'r') as myfile:
        get_aaa(myfile)
        get_bbb(myfile)
        get_fff(myfile)
但这确实:

def main():
    with open('myinputfile.txt', 'r') as myfile:
        get_aaa(myfile)
    with open('myinputfile.txt', 'r') as myfile:
        get_bbb(myfile)
    with open('myinputfile.txt', 'r') as myfile:
        get_fff(myfile)
答案就在于,这些文件。所以在你经历了这一切之后,你就可以“倒带”回去了。这可以通过以下方法完成

我还没有测试,但这段代码应该可以工作:

def main():
    with open('myinputfile.txt', 'r') as myfile:
        get_aaa(myfile)
        myfile.seek(0)
        get_bbb(myfile)
        myfile.seek(0)
        get_fff(myfile)
但我认为使用字符串变量会更好,请参阅。这里的区别是,字符串是无状态且不可变的,因此其行为比文件对象更可预测。

1 2.
这是一个恰当的问题。非常令人耳目一新。在基于测试和推断创建最小示例方面做得很好