您好我试图一次读取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])
...
我怎样才能实现这个目标
*欢呼声
和任何帮助的人
答案 0 :(得分: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
...
答案 1 :(得分: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
答案 2 :(得分: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]
未经测试
答案 3 :(得分: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
答案 4 :(得分: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]