首页 > 解决方案 > 文件内容不打印

问题描述

我是初学者,正在使用 python 3.7 学习编程。我正在运行一个基本程序来在写入文件后读取文件的内容。但是打印功能不会在终端上打印出文件的内容。你能纠正我在这里犯的错误吗:

spam = input("What file would you like to open. Type the name below\n>>>")
# for the file name I type example.txt
work = open(spam, "r+")
work.write(input("Now write something on the file here\n>>"))
x = work.read()
print(x)


work.close()

标签: python-3.xfileread-write

解决方案


完成后write(),需要将文件的对象索引移动到文件的开头

在操作work.seek(0)前添加read()

spam = input("What file would you like to open. Type the name below\n>>>")
# for the file name I type example.txt
work = open(spam, "r+")
work.write(input("Now write something on the file here\n>>"))
work.seek(0)
x = work.read()
print(x)


work.close()

推荐阅读