I have a very big txt file. I want to read through each line of the file and get an input based on the 3rd element of the file(list).
So, I convert the text file to list and iterate through each element of the list to get my desired output.
This is a part of my txt file:
34566---There was no file in there---Mr. [email protected]
36122---I found the file in [email protected]
64322
28890---I went to see the crowd---Henry [email protected]
44533---The weather made it perfect---Merry [email protected]
This is the code that I used:
value = input("Enter your name:")
filename = open("test.txt", "r")
for line in filename:
line_num = line.strip('\n').split("---")
if line_num [2] == value:
print(line_num[1])
break
The only problem is the value in the middle doesnot behave as the other elements in the list. So, it is giving an error
IndexError: list index out of range
I don't know how to code to ignore the middle element which doesnot behave as the rest of the elements in the list. Please help me.
CodePudding user response:
You can try this,
value = input("Enter your name:")
filename = open("anotherSix.txt", "r")
for line in filename:
if line == '\n':
continue
line_num = line.strip('\n').split("---")
if line_num [2] == value:
print(line_num[1])
break
As You can see I added only the if line == '\n': continue
part which basically skips the empty line
CodePudding user response:
Change your condition to:
if len(line_num) > 2 and line_num [2] == value: