你好,我正在尝试一次读取8行Python格式的文件,并使用当前的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表示任何帮助。
发布于 2012-12-17 14:17:00
使用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-17 14:26:05
一次使用通常的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-17 14:16:09
这个怎么样:-
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]未经测试的
https://stackoverflow.com/questions/13909150
复制相似问题