小编Dav*_*idW的帖子

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

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

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

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

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
Run Code Online (Sandbox Code Playgroud)

这是我的代码中有问题的部分。

def main():
    with open('myinputfile.txt', 'r') as myfile:
        get_aaa(myfile)
        get_bbb(myfile)
        get_fff(myfile)
Run Code Online (Sandbox Code Playgroud)

每个 get_xxx 函数只是搜索一个字符串。get_aaa() 搜索 ^aaa,get_bbb() 搜索 ^bbb,get_fff() 搜索 ^fff。如果找到该字符串,该函数将打印一些文本以及匹配的行。如果未找到该字符串,则会打印“NOT FOUND”消息。

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

Start Date:  aaa this is line 1
ITEM BBB: NOT FOUND
ITEM FFF: NOT FOUND
Run Code Online (Sandbox Code Playgroud)

当我修改 main() 并重新排序以在 get_aaa() 之前调用 …

python-3.x

5
推荐指数
1
解决办法
1054
查看次数

标签 统计

python-3.x ×1