【问题标题】:Python Read() Function Reading N Lines at a time [duplicate]Python Read()函数一次读取N行[重复]
【发布时间】:2012-12-04 20:27:48
【问题描述】:

可能重复:
Python how to read N number of lines at a time
Read a File 8 Lines at a Time Python

我正在尝试一次读取 8 行的文件,然后在我的代码中使用这些值作为变量

问题是读取它的方式或读取它的方法在我的代码中不能作为字符串变量使用

使用 Read 似乎有效,但我不知道如何使用 read() 函数一次读取 8 行文件。

知道我该怎么做吗?

谢谢

编辑更多细节

我正在使用库 spynner。我可以使用任意数量的代码一次读取文件 n 行,但实际上将这些行用作 spinner 函数中的值是行不通的。例如

我用它来读取文件

with open("test.txt") as fin:
    try:
        while True:
            data =  islice(fin, 0, 8)                
            email = next(data)

然后在 Spynner 我这样做

browser.wk_fill('input[name="email"]', email)

表格中没有填写的内容。我不是在构建机器人,也不是垃圾邮件工具,只是在胡闹。

感谢任何反馈/帮助

*干杯

【问题讨论】:

标签: python


【解决方案1】:

read 从文件中读取多个字节。你想要readline 一直读到行尾。调用八次得到八行:

[f.readline() for _ in range(8)]

或者,您可以使用one of the itertools recipes 将文件分组为八行块,然后对其进行迭代:

from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

for block in grouper(8, f):
    # do stuff
    pass

这是可行的,因为迭代 f 与迭代其行相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 2018-01-08
    • 2021-11-30
    • 2011-11-13
    • 1970-01-01
    • 2019-02-09
    • 2013-04-11
    相关资源
    最近更新 更多