我有这个文本文件:
[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
和一些代码
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)
如果找到字符串"cat /etc/passwd"
,它会将下几行存储在变量cat
输出:
root:!:0:0::/:/usr/bin/ksh
daemon:!:1:1::/etc:
bin:!:2:2::/bin:
如果我从for循环中调用cat
,就是这种情况。如果我在for循环之外调用它,我只得到最后一行:
bin:!:2:2::/bin:
我认为行for i in range(3)
就是这个原因。有没有办法我可以在循环外调用cat
并让它返回我想要打印的每一行?
答案 0 :(得分:3)
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
阅读python列表。
答案 1 :(得分:1)
对于每次迭代,您都会覆盖cat的最后一个值。
在循环内部,每次覆盖之前都会打印。在循环之外,您只打印其最后一个值。
您可以将结果存储在数组中
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
答案 2 :(得分:0)
你试过这个吗?
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)
答案 3 :(得分:0)
iteration
(for lines in f2
)和read method
(f2.readline
)的混合并不好。我有一个itertools.islice
的其他解决方案,只使用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
是list
,就像Alex