0

您好我正在尝试一次读取 Python 8 行中的文件并将当前的 8 行用作 str 变量

但是我无法正确执行此操作,希望能提供任何帮助

with open("test.txt", 'r') as infile:
    lines_gen = islice(infile, 8)
    for lines in lines_gen:
        firstname = str(lines[0])
        lastname = str(lines[1])
        email = str(lines[2])

...

我怎样才能做到这一点

*干杯

和 ty 寻求帮助

4

5 回答 5

3

一次使用通常的 n 个事物模式

from itertools import izip

with open("test.txt") as f:
    line_gen = izip(*[f]*8)
    for lines in line_gen:
        print lines
        firstname, lastname, email, fourth, fifth, sixth, seventh, eighth = lines
        ...
于 2012-12-17T06:26:04.583 回答
2

使用 itertools.islice 的简单实现

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

            firstname = next(data)
            lastname = next(data)
            email = next(data)
            #.....
    except StopIteration:
        pass

一个更好的pythonic实现

>>> from collections import namedtuple
>>> from itertools import islice
>>> records = namedtuple('record',
                  ('firstname','lastname','email' #, .....
               ))
>>> with open("test.txt") as fin:
    try:
        while True:
            data =  islice(fin, 0, 3)

            data = record(*data)
            print data.firstname, data.lastname, data.email #.......
    except (StopIteration, TypeError):
        pass
于 2012-12-17T06:17:00.393 回答
1

这个怎么样 :-

with open("test.txt", 'r') as infile:
    lines_gen = infile.readlines()
    for i in range(0, len(lines_gen), 8):
        (firstname, lastname, email, etc1, ..) = lines_gen[i:i+8]

未经测试

于 2012-12-17T06:16:08.677 回答
0
with open("test.txt", 'r') as infile:
    it = iter(infile)
    while True:
        lines_list = []
        try:
            for i in range(8):
                lines_list.append(next(it))
        except StopIteration:
            if len(lines_list) == 0:
                break
        for eight_lines in lines_list:
            # Do something with eight_lines[0:8]
于 2012-12-17T06:33:09.187 回答
0

尝试这个:

every_eight = []
lines = open('test.txt').readlines()
j = 0
for n in range(0, len(lines) +1, 8):
    every_eight.append(''.join([lines[l] for l in range(j, n)]))
    j = n

顺便说一句,如果你想接受大量人或某事的大量输入,你可以尝试在这样的列表中使用字典:

info = []

every_eight = []
lines = open('test.txt').readlines()
j = 0
for n in range(0, len(lines) +1, 8):
    every_eight.append([lines[l] for l in range(j, n)])
    j = n

for setinf in every_eight:
    if len(setinf) == 8:
        info.append({
                'firstname': setinf[0],
                'lastname' : setinf[1],
                'email'    : setinf[2],
            })

for inf in info:
    print inf
于 2012-12-17T06:27:39.850 回答