簡體   English   中英

如何將每行的第一個單詞讀入文件中的一行

[英]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])          

將輸出:

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

我希望它從文件中輸出/讀取它:

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

將單詞保存到列表中,然后將它們加入空格:

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))

輸出:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM