简体   繁体   中英

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,

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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM