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

Python写入文件后调用f.read()返回空字符串问题求助

Got it! The issue here is all about the file pointer's position after writing to the file. Let me break it down simply:

When you run f.write("YOOO!!!"), the file pointer moves to the end of the text you just added. So when you call f.read() right after, it starts reading from that end position—there’s nothing left to read beyond that point, hence the empty string.

Here are a few ways to fix this:

Fix 1: Reset the file pointer to the start

Use f.seek(0) to move the pointer back to the beginning of the file before reading:

f = open("test.txt", 'w+')
f.write("YOOO!!!")
f.seek(0)  # Move pointer back to the start of the file
data = f.read()
print(data)  # Output: YOOO!!!
f.close()

Fix 2: Close and reopen the file

After writing, close the file and reopen it in read mode—this automatically resets the pointer to the start:

f = open("test.txt", 'w+')
f.write("YOOO!!!")
f.close()

# Reopen in read-only mode
f = open("test.txt", 'r')
data = f.read()
print(data)  # Output: YOOO!!!
f.close()

Fix 3: Use with statements (best practice)

with statements handle file closing automatically, even if an error occurs. This is the cleanest and safest approach:

# Write to the file
with open("test.txt", 'w') as f:
    f.write("YOOO!!!")

# Read from the file
with open("test.txt", 'r') as f:
    data = f.read()
    print(data)  # Output: YOOO!!!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:30:35