简体   繁体   中英

Python - Extracting data from a text file (list index out of range)

I created a script to extract weekdays from lines in a text file (email data) starting with 'From:'. I successfully did so and then as part of an exercise I need to modify the text file such that it causes a bug. To do this I added an extra line 'From' to line 1 of the text file (image below) which causes the original code to not work and throw an error. To debug the script, I added an if-statement to first check whether the array is greater than length of 0 to proceed with the print statement, although this does not work. What is the most efficient way of resolving this error?

Original code:

fhand = open('mbox-short.txt')
count = 0
for line in fhand:
    if line == '': continue
    line = line.rstrip()
    words = line.split()
    if words == []: continue
    if words[0] != 'From' : continue
    print(words[2])

Modified:

修改后的文本文件

Code:

fhand = open('mbox-short (will fail).txt')
count = 0
for line in fhand:
    if line == '': continue
    line = line.rstrip()
    words = line.split()
    if words == []: continue
    if words[0] != 'From' : continue
    if len(words) >0:
        print(words[2])

OUTPUT:

File "C:\Users\User\Desktop\Chapter 8\8.2 - #2.py", line 9, in <module>
    print(words[2])

IndexError: list index out of range

Thank you Aditya, the issue was that lines containing less than 3 words were being stored in the list (these could not possibly contain the day). As a result, when index 3 was referenced, it threw an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM