You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python3在words.txt单词间插入Morning并写入newfile.txt?

实现Python3在单词间插入指定内容并写入文件

代码实现

# 读取源文件内容
with open('words.txt', 'r', encoding='utf-8') as src_file:
    # 提取有效单词并去除换行符
    words = [line.strip() for line in src_file if line.strip()]

# 将每个单词转为首字母大写格式
formatted_words = [word.capitalize() for word in words]

# 构造包含插入内容的结果列表
output_lines = []
for word in formatted_words:
    output_lines.append(word)
    output_lines.append('Morning')

# 移除最后多余的"Morning"
if output_lines:
    output_lines.pop()

# 将结果写入目标文件
with open('newfile.txt', 'w', encoding='utf-8') as dest_file:
    dest_file.write('\n'.join(output_lines))

关键说明

  • 用with语句操作文件,无需手动关闭文件,保证资源安全
  • 处理源文件时过滤空行,避免无效内容干扰
  • capitalize()方法统一单词首字母大写,匹配需求中的输出格式
  • 通过循环在每个单词后添加"Morning",最后移除末尾多余的插入内容,保证格式正确
  • 用'\n'.join()将列表转为换行分隔的字符串,直接写入目标文件

内容的提问来源于stack exchange,提问作者Gomenburu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 10:40:33