打印每一行的最简单方法是什么?

时间:2017-10-28 21:03:25

标签: python-3.x

我有一个文本文件(我们称之为sample.txt),它由750行文本组成。我想将整个第二行放在一个列表中,然后是每第8行(即第10行,然后是第18行,然后是第26行,依此类推)。

sam_file = open("sample.txt")
sam_lines = seq_sample.readlines

但那又怎么样?我试过的迭代方法只是从第一行抓取第二,第十等字符,但我知道它必须是一个相当简单的for循环。

2 个答案:

答案 0 :(得分:1)

itertools救援:

<<>> DiG 9.8.3-P1 <<>> rendezvous.runtime.heroku.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 49376
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 13, ADDITIONAL: 5

;; QUESTION SECTION:
;rendezvous.runtime.heroku.com. IN  A

;; ANSWER SECTION:
rendezvous.runtime.heroku.com. 450 IN   CNAME   ec2-50-19-103-36.compute-1.amazonaws.com.
ec2-50-19-103-36.compute-1.amazonaws.com. 604800 IN A 50.19.103.36

;; AUTHORITY SECTION:
compute-1.amazonaws.com. 1  IN  NS  pdns1.ultradns.net.
compute-1.amazonaws.com. 1  IN  NS  ns4.p31.dynect.net.
compute-1.amazonaws.com. 1  IN  NS  pdns3.ultradns.org.
compute-1.amazonaws.com. 1  IN  NS  u4.amazonaws.com.
compute-1.amazonaws.com. 1  IN  NS  u3.amazonaws.com.
compute-1.amazonaws.com. 1  IN  NS  ns3.p31.dynect.net.
compute-1.amazonaws.com. 1  IN  NS  ns2.p31.dynect.net.
compute-1.amazonaws.com. 1  IN  NS  pdns5.ultradns.info.
compute-1.amazonaws.com. 1  IN  NS  u6.amazonaws.com.
compute-1.amazonaws.com. 1  IN  NS  u1.amazonaws.com.
compute-1.amazonaws.com. 1  IN  NS  ns1.p31.dynect.net.
compute-1.amazonaws.com. 1  IN  NS  u5.amazonaws.com.
compute-1.amazonaws.com. 1  IN  NS  u2.amazonaws.com.

;; ADDITIONAL SECTION:
pdns1.ultradns.net. 1970    IN  A   204.74.108.1
pdns1.ultradns.net. 1970    IN  AAAA    2001:502:f3ff::1
ns3.p31.dynect.net. 69968   IN  A   208.78.71.31
pdns3.ultradns.org. 12753   IN  A   199.7.68.1
pdns3.ultradns.org. 43539   IN  AAAA    2610:a1:1015::1

;; Query time: 72 msec
;; SERVER: 152.19.240.8#53(152.19.240.8)
;; WHEN: Sat Oct 28 19:50:08 2017
;; MSG SIZE  rcvd: 500`

根据您对内容的处理方式,最好将操作保留在上下文管理器中,或者将文件内容保存在内存中(通过执行with open('sample.txt') as sam_file: # always open files with context managers sam_lines = itertools.islice(sam_file, 1, None, 8) # do your stuff with the context 左右)

答案 1 :(得分:1)

你能尝试这样的事吗?

from itertools import islice
with open('sample.txt') as f:
    for line in islice(f, 2, None, 8):
        print line,