Python Forum
Print text file problems - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Print text file problems (/thread-4379.html)



Print text file problems - Fran_3 - Aug-11-2017

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()



RE: Print text file problems - Larz60+ - Aug-11-2017

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()



RE: Print text file problems - snippsat - Aug-12-2017

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



RE: Print text file problems - Fran_3 - Aug-12-2017

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 !!!