Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I read only the first word of each line of a text file?

I wanted to know how I could read ONLY the FIRST WORD of each line in a text file. I tried various codes and tried altering codes but can only manage to read whole lines from a text file. The code I used is as shown below:

QuizList = []
with open('Quizzes.txt','r') as f:
            for line in f:
                QuizList.append(line)
        line = QuizList[0]
        for word in line.split():
            print(word)

This refers to an attempt to extract only the first word from the first line. In order to repeat the process for every line i would do the following:

QuizList = []
with open('Quizzes.txt','r') as f:
            for line in f:
                QuizList.append(line)
capacity = len(QuizList)
capacity = capacity-1
index = 0
while index!=capacity:
    line = QuizList[index]
    for word in line.split():
        print(word)
        index = index+1
like image 578
Hamzah Akhtar Avatar asked Dec 01 '22 19:12

Hamzah Akhtar


1 Answers

You are using split at the wrong point, try:

for line in f:
    QuizList.append(line.split(None, 1)[0]) # add only first word
like image 176
jonrsharpe Avatar answered Dec 04 '22 08:12

jonrsharpe