如何在Python中打印文件的特定行

时间:2018-09-13 06:38:37

标签: python

我有一个.txt文件,我想打印3, 7, 11, 15,...

因此,在打印第三行之后,我想在以后每四行打印一次。

我首先看一下模运算符:

#Open the file
with open('file.txt') as file:

  #Iterate through lines
  for i, line in enumerate(file):

      #Choose every third line in a file
      if i % 3 == 0:
          print(line)

  #Close the file when you're done
  file.close()

但是这种方法每三行打印一次。如果i % 3 == 1显示行1、4、7、10、13等。

5 个答案:

答案 0 :(得分:3)

除了模数外,您的代码几乎可以用:您希望除以4的余数为3。

with open('file.txt') as file:
  for i, line in enumerate(file):
      if i % 4 == 3:
          print(line)

请注意,您无需在结尾处明确地close文件:这就是with的用途,它可以确保无论发生什么情况,文件都被关闭。

答案 1 :(得分:1)

因此,您希望每隔第四次发生某事,这意味着取模4。尝试将if更改为if i % 4 == N:,并为N设置一个合适的数字。

顺便说一句,当使用with语句时,您不必调用close(),它会自动调用。

答案 2 :(得分:1)

怎么样:

# Fetch all lines from the file
lines = open('20 - Modular OS - lang_en_vs2.srt').readlines()

# Print the 3rd line
print(lines[2])

# throw away the first 3 lines, so the modulo (below) works ok
for i in range(3):
    del(lines[0])

# print every 4th line after that
for (i in range(len(lines)):
    if (i > 0 and i % 4 == 0):
        print(lines[i])

将每一行读入数组。 输出第三行。 然后,我们需要每四行,因此,通过删除前三个元素,可以轻松地对模4(“%4”)进行测试并输出该行。

答案 3 :(得分:0)

x = 0
with open('file.txt') as file:

  #Iterate through lines
  for i, line in enumerate(file):
      x += 1
      #Choose every third line in a file
      if x == 4:
          print(line)
          x = 0

  #Close the file when you're done
  file.close()

结果

>>> i = 0
>>> for x in range(0, 100):
...     i += 1
...     if i is 4:
...         print(x)
...         i = 0

3 7 11 15 19 23 27 31 35 39 43 47 51 55 59 63 67 71 75 79 83 87 91 95 99

答案 4 :(得分:0)

file = open('file.txt')
print(file[2])
#Iterate through lines
for i in file:
  #Choose every third line in a file, beginning with 4
  if i % 4 == 0:
      print(i+3)
  elif i % 4 == 0:
      print(i)

这行得通,但不是超级优雅。