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

Python中fileinput.input以'r'模式读取文件却被覆盖的问题求助

问题原因与解决方案
  • 问题根源:你调用fileinput.input()的方式有误。这个函数的第二个位置参数不是文件模式'r',而是inplace(原地编辑)参数。当你传入'r'时,Python会将其判定为布尔值True,直接开启了原地编辑模式。在这种模式下,fileinput会把程序的输出重定向到临时文件,执行完成后用临时文件替换原文件——哪怕你给print指定了file=None(默认stdout),输出也会被这个机制劫持,最终导致原文件被覆盖。

  • 正确处理方式:

    1. 如果坚持用fileinput,必须用关键字参数指定读取模式,不要误用位置参数:
    import fileinput
    import re
    
    for file in file_args:
        print(f"searching {file}...")
        # 用关键字参数明确指定mode,避免触发inplace模式
        with fileinput.input(files=file, mode='r') as f:
            for line in f:
                from_match = re.search(f"^From:.*({args.text[0]}).*", line)
                subj_match = re.search(f"^Subject:.*({args.text[0]}).*", line)
    
                if from_match or subj_match:
                    print("\n" + "-" * 75 + "\n")
                    print(f"found \"{args.text[0]}\" in {file}...\n")
    
    1. 更推荐直接用普通open()函数(毕竟你只是读取文件,不需要修改):
    import re
    
    for file in file_args:
        print(f"searching {file}...")
        with open(file, 'r') as f:
            for line in f:
                from_match = re.search(f"^From:.*({args.text[0]}).*", line)
                subj_match = re.search(f"^Subject:.*({args.text[0]}).*", line)
    
                if from_match or subj_match:
                    print("\n" + "-" * 75 + "\n")
                    print(f"found \"{args.text[0]}\" in {file}...\n")
    

补充:fileinput的设计初衷是批量原地修改文件(比如批量替换文本内容),单纯读取文件的话,open函数更直观,也不容易踩参数顺序的坑。

内容的提问来源于stack exchange,提问作者Robb Aley Allan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 00:28:11