Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (45.3k points)

I'm trying to write some code that reads a text file and prints the 1st letter of each line. My current code is:

f=open("testfile1.txt","r")

for line in f:

    words=line.split()

    print(words[0])

With this, the strings should be split into the individual words, but when I run the code, I get an error message saying list index out of range. I have tried the solutions of similar questions people had on the same topic, but when I use the same code, I get this error. Can anyone explain why this is happening, and how I can fix it? Thanks

1 Answer

0 votes
by (16.8k points)

Looks like there are few empty lines, try this, it will work:

f=open("testfile1.txt","r")

for line in f:

    words=line.split()

    if words:

        print(words[0])

f.close()

Using, with open :

with open("testfile1.txt", "r") as f:

    for line in f:

        words = line.split()

        if words:

            print(words[0])

Related questions

0 votes
1 answer
asked Jul 26, 2019 in Python by selena (1.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 30, 2019 in Python by Eresh Kumar (45.3k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.5k answers

500 comments

108k users

Browse Categories

...