【发布时间】:2022-12-20 01:31:25
【问题描述】:
任务: 创建一个解决方案,它接受标识文本文件名称的输入,例如“WordTextFile1.txt”。每个文本文件包含三行,每行一个词。使用 open() 函数和 write() 和 read() 方法,与输入文本文件交互,将由三个现有单词组成的新句子字符串写入新行的文件内容末尾。输出新的文件内容。
解决方案输出应采用以下格式 猫 追逐 狗 猫追狗
“WordTextFile1.txt”在不同的行中每个只有 3 个单词 猫 追逐 狗
这就是我所拥有的,但是句子的最后一行有一个额外的空格,这破坏了我的程序。我该怎么做才能摆脱空白并修复我的代码?帮助!
file = input()
with open(file, "r+") as f:
list_words = f.readlines()
for word in list_words:
print(word.strip())
for word in list_words:
print(word.strip(), end = " ")
this is current output:
student
reads
book
student reads book(extra whitespace)
【问题讨论】:
-
先加入,再打印。