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

使用pyfakefs写入后读取未返回预期值的问题排查

pyfakefs写入后读取为空的问题解决

这不是pyfakefs的功能问题,是你对文件指针的操作逻辑有误。

当用w+模式打开文件并写入内容后,文件指针会停在写入内容的末尾位置。此时直接调用read(-1)会从当前指针位置开始读取,自然读不到任何内容——这和真实文件系统的行为完全一致,pyfakefs只是模拟了真实的文件系统行为。

修改测试代码,在读取前将文件指针移到文件开头即可:

import os

def test_filesystem(fs):
    with open("fooey.txt", "w+") as my_file:
        my_file.write("Hello")
        my_file.seek(0)  # 将文件指针移到开头
        read = my_file.read(-1)
        assert os.path.exists("fooey.txt")
        assert "Hello" in read

执行修改后的测试,两个断言都会正常通过。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 01:22:02