简体   繁体   中英

How to print specific lines of a file in Python

I have a .txt file and I would like to print lines 3, 7, 11, 15,...

So, after printing the third line, I would like to print every 4th line afterward.

I began by looking at the modulus operator:

#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()

but that approach prints every third line. If i % 3 == 1 that prints lines 1, 4, 7, 10, 13 etc.

Instead of using modulo, simply just use addition, start it with the first line you want to show, and then add 4 to it

next_line = 2  # Line 3 is index 2
for i, line in enumerate(file):

    if i == next_line:
        print(line)
        next_line = next_line + 4

Your code is almost fine, except for the modulo: you want the remainder of the division by 4 to be 3.

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

Note that you don't need to explicitely close your file at the end: that's what with is intended for, it makes sure that your file gets closed whatever happens.

So you want to something to happen every fourth time, that means modulo 4. Try changing your if to if i % 4 == N: with a good number for N .

By the way, when using the with statement you have don't have to call close() , it does so automatically.

How about:

# 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])

Read every line into an array. Output the 3rd line. We then need every fourth line, so by deleteing the first 3 elements, it's easy to simply test against modulo 4 (the "% 4") and output the line.

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()

Result

>>> 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

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)

This works, but isn't super elegant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM