Skip to content
Advertisement

how to Read a row starting with a specific integer in text file python?

My problem is that I need to read and print a specific line starting with a specific integer(input by user) from text file.

This is my text file information:

1 , ‘USA’ , 7244184 , 53629 , 208440 , 895

2 , ‘Mexico’ , 715457 , 5408 , 75439 , 490

3 , ‘Ireland’ , 33995 , 319 , 1797 , 3

4 , ‘India’ , 5901571 , 85468 , 93410 , 1093

5 , ‘Turkey’ , 311455 , 7858 , 7858 , 73

8 , ‘Qatar’ , 124650 , 220 , 212 , 2

example:

if user entered code = 8

I need the program to print [8,Qatar,124650,220,212,2]

what should I do?

Advertisement

Answer

n = int(input())

with open('./file.txt') as f:

    content = f.read().splitlines()

    for line in content:

        if int(line[0]) == n:
            elements = line.split(',') # a list of individual elements
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement