手动读取 python 中的行

Manually read lines in python

我有一个文件,文件名换行,然后是文件的哈希值,然后换行。这种模式重复。示例:

blah.txt
23847EABF8742
file2.txt
1982834E387FA

我有一个名为 'information' 的 class,它有两个成员变量。

class information:
     filename=''
     hashvalue=''

现在我想读入文件并将文件名和哈希值存储在 'information' 对象的新实例中,然后将信息对象的实例推送到列表中。

我遇到的问题是遍历文件以读取它。我想逐行阅读它直到文件末尾。 python 的 'for line in file' 方法的问题在于它每次都抓取一行,我将被迫执行某种其他策略以将数据放入正确的成员变量中。

相反,这就是我想要做的...

list=[]
while(not end of file)
    x = information()
    x.filename = file.readline()
    x.hashvalue = file.readline()
    list.append(x)
while True:
    x = information()
    x.filename = file.readline()
    if not x.filename:
       break
    x.hashvalue = file.readline()
    my_list.append(x)

也许吧?

while True:
    x = information()
    try:
        x.filename = next(file)
        x.hashvalue = next(file)
    except StopIterationError:
        break
    my_list.append(x)

或者我最喜欢的

my_list = [filename,hashvalue for filename,hashvalue in zip(file,file)]

你可以写一个生成器函数:

def twolines(file):
    cur = None
    for i in file:
        if cur is None:
            cur = i
        else:
            yield (cur, i)
            cur = None

然后将您的文件对象传递给 twolines(),然后执行类似

的操作
for i, j in twolines(file):
    x = information()
    x.filename, x.hashvalue = i,j
    list.append(x)

这个怎么样:

list = [information(filename=x.rstrip(), hashvalue=next(it).rstrip()) for x in file]

另一个简单的修复方法是计算行数。为此引入一个像 line = 0 这样的变量。现在您可以尝试以下操作:

for lines in file:
    line = line + 1
    if line  % 2 == 1:
        # This will be the filename
    else:
        # This will be the hashcode