Python Forum

Full Version: Print text file problems
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a text file test.txt with contents separated by a comma like
Mary,Teacher
John,Admin
Joan,Boss

But when I run the code below the x[1] element creates an error
IndexError: list index out of range
this is from the online tutorial at https://www.youtube.com/watch?v=dkLTmpldS-w
What am I doing wrong?
Thanks for any help

print('to split lines into elements')
fp = open ("c:\\test\\test.txt", "r")
for line in fp:
    x=line.split(",")       #splits line at comma
    print(x[0],'\t',x[1])   #print the two items on the line with a tab
#    print(x[0])            #comment out the above line and un-comment this and I get the x[0] element
fp.close()
Modify your code as follows, and report results:
print('to split lines into elements')
fp = open ("c:\\test\\test.txt", "r")
for line in fp:
    x=line.split(",")       #splits line at comma
    print('len(line): {}, line: {}'.format(len(line), line))
    print('x: {}'.format(x))
    print(x[0],'\t',x[1])   #print the two items on the line with a tab
#    print(x[0])            #comment out the above line and un-comment this and I get the x[0] element
fp.close()
You should't get IndexError uncomment or not with the code you show here.

Just to make a more modern Python version.
import csv

with open("test.txt") as fp:
    reader = csv.reader(fp, delimiter=',')
    for row in reader:
        print(f'{row[0]}\t{row[1]}')
Output:
Mary    Teacher John    Admin Joan    Boss
Works now.
Turns out problem was an extra blank line at the end of the text file. Your code help me zero in on it.
Thanks again for the help !!!