当我尝试在 Python 中的文件上使用 read() 函数时,输出为空

  • 本文关键字:函数 read 输出 Python 文件 python
  • 更新时间 :
  • 英文 :


这是我尝试过的代码:

test = open('test.txt', 'w+')
test.write('test')
print(test.read())

我在Visual Studio Code上使用Python的3.8.2版本。 当我运行它时我没有收到任何错误,但输出是空的。 我做错了什么吗?

您需要使用格式'r+',并seek

with open('test.txt', 'r+') as test:
test.write('test')
test.seek(0) # seek lets us from which index we want to start reading
print(test.read())

最新更新