Reputation: 602
I have this text file:
[admin]# cat /etc/passwd
root:!:0:0::/:/usr/bin/ksh
daemon:!:1:1::/etc:
bin:!:2:2::/bin:
sys:!:3:3::/usr/sys:
adm:!:4:4::/var/adm:
uucp:!:5:5::/usr/lib/uucp:
guest:!:100:100::/home/guest:
nobody:!:4294967294:4294967294::/:
lpd:!:9:4294967294::/:
lp:*:11:11::/var/spool/lp:/bin/false
invscout:*:200:1::/var/adm/invscout:/usr/bin/ksh
nuucp:*:6:5:uucp login user:/var/spool/uucppublic:/usr/sbin/uucp/uucico
paul:!:201:1::/home/paul:/usr/bin/ksh
jdoe:*:202:1:John Doe:/home/jdoe:/usr/bin/ksh
and some code here
with open(file) as f2:
for lines in f2:
if "cat /etc/passwd" in lines:
for i in range(3):
cat = f2.readline()
print(cat)
if it finds the string "cat /etc/passwd"
, it will store the next couple of lines inside the variable cat
output:
root:!:0:0::/:/usr/bin/ksh
daemon:!:1:1::/etc:
bin:!:2:2::/bin:
This is the case if I call cat
from inside the for loop. If I call it outside of the for loop, I only get the last line :
bin:!:2:2::/bin:
I assume the line for i in range(3)
is the reason for this. is there a way I can call cat
outside the loops and have it return each of the lines I want printed?
Upvotes: 0
Views: 493
Reputation: 1938
The mixing of iteration
(for lines in f2
) and read method
(f2.readline
) is not nice. I have a other solution with itertools.islice
, which only uses iteration
from itertools import islice
with open(file) as f2:
for line in f2:
if "cat /etc/passwd" in lines:
cat = list(islice(f2, 3))
print cat
cat
is a list
like the answer of Alex
Upvotes: 0
Reputation: 1
Have you tried this ?
cat = ''
with open(file) as f2:
for lines in f2:
if "cat /etc/passwd" in lines:
for i in range(3):
cat += f2.readline()
print(cat)
Upvotes: 0
Reputation: 184
For each iteration you overwrite the last value of cat.
Inside of the loop, you print each time before you overwrite. Outside of the loop, you only print its last value.
You could store your results in an array
with open(file) as f2:
for lines in f2:
if "cat /etc/passwd" in lines:
cat = []
for i in range(3):
cat.append(f2.readline())
print cat[i]
for x in cat:
print x
Upvotes: 1
Reputation: 36033
cat = []
with open(file) as f2:
for lines in f2:
if "cat /etc/passwd" in lines:
for i in range(3):
cat.append(f2.readline())
print cat
Read about python lists.
Upvotes: 3