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

Python创建并读取文件无输出问题排查求助

问题分析与解决

嘿,我来帮你搞定这个问题!你的代码里有两个关键细节没处理好,导致控制台没输出,咱们一步步拆解:

1. 文件写入后指针位置不对

当你用write()方法往文件里写完内容时,文件指针会停在文件的末尾。这时候直接调用read(),程序会从末尾开始读取,自然读不到任何内容。

解决办法是在读取前,用seek(0)把指针移回文件开头。

2. 文件关闭方法未正确调用

你写的a.close和b.close只是引用了close方法对象,并没有真正执行关闭操作——正确的写法应该是a.close()和b.close()(要加括号调用方法)。不过更推荐用Python的with语句,它会自动帮你管理文件的打开和关闭,避免这类疏漏。


修正后的代码(基于原写法调整)

# create two new files
a = open("file.txt","w+")
b = open("file2.txt", "w+")
#write to file
a.write("text in english")
b.write("text in english2")

# 关键:将文件指针移回开头
a.seek(0)
b.seek(0)

#read the file & print the text to console
teksts1 = a.read()
teksts2 = b.read()
print(teksts1)
print(teksts2)

# 正确调用close方法
a.close()
b.close()

更优雅的写法(使用with语句)

# 用with语句自动管理文件上下文,无需手动close
with open("file.txt","w+") as a, open("file2.txt", "w+") as b:
    # write to file
    a.write("text in english")
    b.write("text in english2")
    
    # 移回指针后读取
    a.seek(0)
    b.seek(0)
    
    teksts1 = a.read()
    teksts2 = b.read()
    print(teksts1)
    print(teksts2)

这样运行后,控制台就能正常输出文件里的内容啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 13:27:31