Search code examples
pythonfilesplitline

How do I print the 1st word of each line in a txt file?


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.


Solution

  • Sounds like there are empty lines, so the below should work:

    f=open("testfile1.txt","r")
    
    for line in f:
        words=line.split()
        if words:
            print(words[0])
    f.close()
    

    Even better, with open:

    with open("testfile1.txt", "r") as f:
        for line in f:
            words = line.split()
            if words:
                print(words[0])