Read A File 8 Lines At A Time Python
Hello I am trying to read a file in Python 8 lines at a time and use the current 8 lines as str variables However I am unable to do this correctly and would appreciate any help wit
Solution 1:
Using the usual n things at a time pattern
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
...
Solution 2:
A simple implementation using 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
A better more pythonic implementation
>>> 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
Solution 3:
How about this :-
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]
untested
Solution 4:
Try this:
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
By the way, if you're trying to accept mass input for tons of people or something, you could try using dictionaires in a list like this:
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
Solution 5:
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]
Post a Comment for "Read A File 8 Lines At A Time Python"