每次调用函数时都从文件返回新行

时间:2017-03-25 11:09:27

标签: python python-2.7

我正在寻找一段执行以下操作的代码

  • 作为个人功能运行
  • 逐行读取文件
  • 每次调用该函数时,它都会返回文件的下一行。它不是一个随机的行,而是需要一次一行。

伪代码:

 <%= time_select :open_time, :prompt , :default => {:hour => '9', :minute => '30'} ,  html_options: {class: "form-control"} %>

2 个答案:

答案 0 :(得分:1)

这是我最后使用的代码。

def emailToTry():  # Generate a new email from a file
    with open('leakedEmails.txt') as f:  # Using a file of leaked email address, can also use a brute forcer.
        for line in f:
            yield line  # Returns the next line each time it is called

答案 1 :(得分:0)

我从未使用yield,但这就是你想要的

def read_file(file_name):
    f = (open(file_name, "r")).read().splitlines()
    for line in f:
        yield line
    f.close()

file_opened = read_file("test.txt")

for line in file_opened:
    print(line)