How to read specific lines from text file in Python

2 Answers

0 votes
x = 2
y = 4
z = 6
with open('info.txt') as f:
    for i, line in enumerate(f):
        if i == x - 1:
            print(line)
        elif i == y - 1:
            print(line)
        elif i > z - 1:
            break


'''
run:
  
high-level, general-purpose 

python design philosophy emphasizes code readability
  
'''

 



answered Jun 23, 2020 by avibootz
0 votes
x = 2
y = 4
lines_to_read = [x - 1, y - 1]
with open('info.txt') as f:
    for i, line in enumerate(f):
        if i in lines_to_read:
            print(line)
 
 
'''
run:
   
high-level, general-purpose 
 
python design philosophy emphasizes code readability
   
'''

 



answered Jun 23, 2020 by avibootz

Related questions

1 answer 197 views
2 answers 265 views
1 answer 271 views
1 answer 195 views
1 answer 186 views
...