我是一个初学者,正在使用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()
答案 0 :(得分: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 :(得分:-1)
您实际上无法读取垃圾邮件变量,因为它不是文件。 相反:
work = open("NewFile.txt", "w")
work.write(spam)
work.close()