Reputation: 1945
I have a class,com_and_url, containing 2 variable, com and url. Such as:
a = com_and_url(com, url)
And a file I want to read whose content is like this:
Google
www.google.com
yahoo
www.yahoo.com
facebook
www.facebook.com
So here is the psuedo code:
list_com_and_url = []
for com, url in f:
list_com_and_url.append( com_and_url( com, url ) )
Can python do this? Thanks for the help!
Upvotes: 1
Views: 88
Reputation: 107287
As an optimized way in term of memory (using iterators and refusing of loading whole of the lines in memory) you can use itertools.tee()
to create two independent iterator from your file object (which is an iterator) then use itertools.islice()
to put the even lines in f
and odd lines in next_f
then use zip()
function (in python 2 itertools.izip()
) to create an iterator contain the pair columns.
from itertools import tee, islice
with open('my_file') as f:
next_f, f = tee(f)
next_f, f = islice(f, 0, None, 2), islice(next_f, 1, None, 2)
list_com_and_url = [com_and_url( com, url ) for com, url in zip(f, next_f)]
Upvotes: 0
Reputation: 39406
The shortest and (I find) clearest way is using slices:
lines = f.readlines()
for com, url in zip(lines[::2], lines[1::2]):
# Do stuff
(nota: do not attempt this with files that don't fit in memory)
Upvotes: 1
Reputation: 19743
Try this:
list_com_and_url = []
with open('my_file') as f:
for line in f:
name, url = line, next(f)
list_com_and_url.append(zip(name, url))
Upvotes: 2
Reputation: 191728
You can just read two lines at a time
with open('file.txt') as f:
lines = f.read().splitlines()
com_and_url = (lines[i:i+2] for i in range(0, len(lines), 2))
This returns a generator, so to output to a list
print(list(com_and_url))
outputs
[['Google', 'www.google.com'],
['yahoo', 'www.yahoo.com'],
['facebook', 'www.facebook.com']]
Upvotes: 0