![](/img/trans.png)
[英]How can you read just the first word of every line of file using python?
[英]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.