-1

I don't know how to print certain lines of code from a text file. All it is doing nothing when I run the below code.How to read specific lines from the file ?.

line = open ("random.txt",2)
print(line)
line = open ("random.txt",5)
print(line)
line = open ("random.txt",7)
print(line)
line = open ("random.txt",9)
print(line)
line = open ("random.txt",10)
print(line)
myFile.close()

my output can be random string and I don't mind as long as it prints only the set of lines.

Pocketwarloc
  • 1
  • 1
  • 4

2 Answers2

2

open takes a mode as its second argument, not a number. I think what you need is this:

with open("random.txt") as open_file:
    lines = open_file.readlines()
    print(lines[2])
    print(lines[5])
    ...

The with block will take care of closing the file.

zondo
  • 19,901
  • 8
  • 44
  • 83
0
wanted_lines = [2,5,7,9,10]
count = 1
with open('random.txt', 'r') as infile:
     for line in infile:
          line = line.strip()
          if count in wanted_lines:
               print(line)
          else:
               pass
          count += 1
Seekheart
  • 1,135
  • 7
  • 8