Reputation: 33
My text file is laid out like this:
1,jack,Jackson,16,won
2,Dex,Craz,17,loss
3,Bree,Lopson,20,
4,her,ber,12,loss
5,say,huy,34,
6,lol,asw,23,won
7,dert,ker,30,loss
8,far,sas,11,
9,ger,xza,15,
10,yui,caer,66,won
11,opl,guyh,45,
and what I'm trying to do is have the user input a number that they would like to see and print out the information corresponding to that number.
This is my code:
numb = input('Input Line: ')
fiIn = open('Prac.txt').readlines()
for lines in fiIn:
if numb == lines[0]:
data = lines.split(',')
print ('|{0[0]:<15}|{0[1]:<15}|{0[2]:<15}|{0[3]:<15}|{0[4]:<15}'.format(data))
but it doesn't only print the number I want but also other numbers. For example: if I input 1 it would output 1, 10 and 11 not just 1. Any idea on how to do this?
Upvotes: 1
Views: 48
Reputation: 22954
The error is in the comparison line if numb == lines[0]:
where you are checking the input string with the first character of the line and hence it matches all the lines starting with 1
, What you need to do is split the line on ,
and then compare the first element as :
numb = input('Input Line: ')
fiIn = open('Prac.txt').readlines()
for lines in fiIn:
if numb == lines.split(",")[0]:
data = lines.split(',')
print ('|{0[0]:<15}|{0[1]:<15}|{0[2]:<15}|{0[3]:<15}|{0[4]:<15}'.format(data))
Upvotes: 1
Reputation: 7735
split()
lines
first, then check if the first item is your number.
for lines in fiIn:
data = lines.split(',')
if numb == data[0]:
print ('|{0[0]:<15}|{0[1]:<15}|{0[2]:<15}|{0[3]:<15}|{0[4]:<15}'.format(data))
Upvotes: 1