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

开发Python文本审查程序替换4字母词为星号,无法写入输出文件求助

问题排查与修复方案

你代码存在两个核心错误导致无法正常写入文件:

  • 写入文件的逻辑位置错误:print(line.rstrip(), file=outfile)被放在了单词遍历的else分支下,只有当遇到长度不等于4的单词时才会触发写入,且每次触发都会重复写入原始未替换的行,完全没有使用替换后的内容。
  • 未生成替换后的完整行内容:你只把替换后的单词输出到了控制台,没有将替换后的单词重新拼接为完整的行,自然无法写入正确的内容到输出文件。
修复后的完整代码
def censor():      
    infile = open("word.list.txt", "r")
    outfile = open("new.word.list1", "w")

    for line in infile:
        words = line.split()
        new_words = []
        for word in words:
            if len(word) == 4:
                new_word = "****"
            else:
                new_word = word
            # 保留原有的控制台打印逻辑
            print(new_word)
            new_words.append(new_word)
        # 拼接替换后的完整行写入文件
        new_line = ' '.join(new_words)
        print(new_line, file=outfile)

    infile.close()
    outfile.close()

censor()
优化建议

可以使用Python的with上下文管理器处理文件IO,不需要手动调用close()方法关闭文件,避免资源泄漏,简化后的写法如下:

def censor():
    with open("word.list.txt", "r") as infile, open("new.word.list1", "w") as outfile:
        for line in infile:
            new_words = ["****" if len(word) == 4 else word for word in line.split()]
            outfile.write(' '.join(new_words) + '\n')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 14:24:06