Reputation: 15
I have a text file, in which each line has words and spaces in between them. I need to extract only a few words in my text files. I wrote a small code to do the job but i got an error saying "List index out of range". I am not able to figure it out what has happened. Could some one shed some light on my issue? Here is my code snippet Error Message in IDLE ide, My text file contents
f2read = open('NEW1.txt','r+').readlines()
for line in f2read:
if str(line.split()[0]) == '$TIME':
pass
elif line.split()[0].isdigit == True:
print(line.split()[1]
)
If you look at the image in My Text File contents link, i have my sample text where there are values after a 10 digit mobile number. After running my code, it should print only the values. For example: $TIME = 1.0 8105346850 203, 9493915616 160 After running my code, it should print 203 and 160 only.
Upvotes: 0
Views: 111
Reputation: 11922
If there is a single empty line in the file, split()
will return an empty list and it will fail with this error. Are you sure there isn't such a line in the file?
In any case, you can verify that with the code:
f2read = open('NEW1.txt','r+').readlines()
for line in f2read:
split_line = line.split()
if len(split_line) > 0 and split_line[0].isdigit():
print(split_line[1])
Upvotes: 1