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

Python向TXT文件追加字符串时仅写入首字母的问题排查及解决求助

Python向TXT文件追加字符串时仅写入首字母的问题排查及解决求助

各位好,我最近在写一个小脚本,想把words_alpha.txt里的单词按长度分类,分别追加写入到1.txt到8.txt这些文件里(长度1的单词进1.txt,以此类推)。但运行后发现一个奇怪的问题:每个文件里只写入了单词的首字母,而不是整个单词,我实在搞不清哪里出问题了,想请大家帮我看看!

先贴一下我的代码片段:

with open("words_alpha.txt", 'r') as f:
  your_result = [line.split(',') for line in f.read().splitlines()]

for i in your_result:
  for word in i:
    x = len(word)
    print(word)
    if x == 1:
      with open("1.txt", "a") as myfile:
        myfile.write(word)
    if x == 2:
      with open("2.txt", "a") as myfile:
        myfile.write(word)
    if x == 3:
      with open("3.txt", "a") as myfile:
        myfile.write(word)
    if x == 4:
      with open("4.txt", "a") as myfile:
        myfile.write(word)
    if x == 5:
      with open("5.txt", "a") as myfile:
        myfile.write(word)
    if x == 6:
      with open("6.txt", "a") as myfile:
        myfile.write(word)
    if x == 7:
      with open("7.txt", "a") as myfile:
        myfile.write(word)
    if x == 8:
      with open("8.txt", "a") as myfile:
        myfile.write(word)
# 后面对应更长长度的判断逻辑和上面一致

我本来以为print(word)能正常输出整个单词,那写入文件应该也没问题,但实际打开生成的txt文件,里面只有每个单词的第一个字母。比如原文件里的"apple",应该写入5.txt,但5.txt里只有"a",这可把我愁坏了。

我先自己排查了几点:

  • 确认words_alpha.txt里的单词都是完整的,没有奇怪的分隔符;
  • print(word)确实能打出整个单词,说明读取的时候应该是拿到了完整的字符串;
  • 也试过用myfile.write(word + '\n'),结果还是只写首字母加换行,整个单词没进去。

有没有大佬能帮我分析下问题出在哪?或者有没有更合理的写法能实现我的需求?麻烦大家了!

备注:内容来源于stack exchange,提问作者Soapy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.16 12:49:38