Home > OS >  How to read first word of every line, into one line in a file
How to read first word of every line, into one line in a file

Time:06-04

with open("my_file.txt", "r") as f:
     next(f)                         # used to skip the first line in the file
     for line in f:
         words = line.split()        
         if words:
            print(words[0])          

Will output:

a-1,
b-2,
c-3,

I want it to output/read this from the file:

a-1, b-2, c-3,

CodePudding user response:

Save the words into a list then join them on spaces:

with open("my_file.txt", "r") as f:
    first_words = []
    next(f)
    for line in f:
        words = line.split()
        if words:
            first_words.append(words[0])
    
print(' '.join(first_words))

Output:

a-1, b-2, c-3,
  • Related