python-3.x - 文件内容不打印
问题描述
我是初学者,正在使用 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()
解决方案
完成后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()
推荐阅读
- python - 日期范围超出月份
- android - 重新打开片段后片段中的 ViewBinding Null 异常错误
- javascript - ElectronJS - 自定义协议客户端后获取信息
- django - Django Many-To-One IntegrityError
- css - 覆盖嵌套变量时,CSS 变量嵌套的行为不符合预期
- c++ - 使用 C++ 概念重载不同模板类型的运算符
- java - Maven 包范围
- php - 未定义的属性:Illuminate\Database\MySqlConnection::$Id
- heroku - 是否可以在 Heruku 帐户之间的 circleci 中分离环境?
- javascript - GSTR-1 GSTR-2 GSTR-3B 的 JSON 格式是什么?