文件内容不打印

问题描述 投票:0回答:2

我是初学者,使用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.x file read-write
2个回答
2
投票

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()

-1
投票

您实际上无法读取垃圾邮件变量,因为它不是文件。代替:

work = open("NewFile.txt", "w")
work.write(spam)
work.close()
© www.soinside.com 2019 - 2024. All rights reserved.