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

为什么Python的read()函数读取文件时返回空内容?

问题根因

你使用a+模式打开文件时,文件操作指针默认定位在文件末尾,直接调用read()会从末尾位置向后读取,自然返回空内容。另外你选择选项2读取文件时,没有添加文件关闭逻辑,会存在文件资源泄漏的问题。

修复方案

有两种常见修复方式可选:

方案1:仅补充指针移动逻辑

在读取文件前调用seek(0)方法将指针移动到文件开头即可,修改后的对应代码片段如下:

elif option == '2':
    myFile.seek(0) # 移动文件指针到开头位置
    AllFileContents = myFile.read()
    print(AllFileContents)
    myFile.close() # 补充文件关闭逻辑

方案2:优化文件操作逻辑(更推荐)

使用with上下文管理器处理文件读写,无需手动控制文件关闭,同时不同操作分开使用对应模式打开文件,避免指针混乱问题,完整代码如下:

print ("(1)Add something to list\n(2)Read my lists")
option = input ("Please select an option: ")
if option == '1':
    ask = input ("What do you want to remember: ")
    with open("Reminder.txt", "a", encoding="utf-8") as myFile:
        myFile.write(ask + "\n")
    print ("Successfully added in database")
elif option == '2':
    with open("Reminder.txt", "r", encoding="utf-8") as myFile:
        AllFileContents = myFile.read()
        print(AllFileContents)
else:
    print ("Please select an existing option!")

内容的提问来源于stack exchange,提问作者Anderson.C

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:36:03