Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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,
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading