鱼C论坛

 找回密码
 立即注册
查看: 3998|回复: 3

[已解决]_io.textiowrapper什么意思

[复制链接]
发表于 2021-8-19 23:12:46 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
第28讲,我在写代码时,进行了这个尝试
  1. with open('OpenMe.mp3', encoding = 'utf-8') as f1:
  2.     m = str(f1)
  3.     print(m)
复制代码


显示内容为:<_io.TextIOWrapper name='OpenMe.mp3' mode='r' encoding='utf-8'>
我不明白:
1. io.TextIOWrapper什么意思?
2. 为什么str(f1)之后,反馈的不是文件中的内容?
最佳答案
2021-8-20 16:21:49
本帖最后由 阿奇_o 于 2021-8-20 16:24 编辑

暂时你不需要明白,_io.TextIOWrapper
真要深究单看这文档https://docs.python.org/3/library/io.html#io.TextIOWrapper
也不完全能解答,因为前面还有个 _io.
所以,你只要知道它是个"对象",是个叫"TextIOWrapper"的对象,然后可以干嘛用的,就行。

其次,str(obj) 其实是 会调用对象obj的__str__方法,故结果是根据__str__方法的定制来的(自定义类里你可以随便怎么写),

  1. In [4]: with open('t.txt', 'r', encoding='utf-8') as f:
  2.    ...:     print(type(f))
  3.    ...:     print(f.__str__())
  4.    ...:
  5. <class '_io.TextIOWrapper'>
  6. <_io.TextIOWrapper name='t.txt' mode='r' encoding='utf-8'>

  7. >>> class Foo:
  8.         def __str__(self):
  9.                 return "我是 假的 <_io.TextIOWrapper name='t.txt' mode='r' ..>"


  10. >>> print(Foo)  # 类的
  11. <class '__main__.Foo'>
  12. >>> print(str(Foo()))   # 对象的 .__str__()
  13. 我是 假的 <_io.TextIOWrapper name='t.txt' mode='r' ..>
  14. >>> f = Foo()
  15. >>> print(f)
  16. 我是 假的 <_io.TextIOWrapper name='t.txt' mode='r' ..>
  17. >>>
  18. >>>
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-8-20 07:45:41 | 显示全部楼层
每种文件都要特定的打开姿势
MP3要用二进制读取,你不写打开方式默认"r",编码好像不要来着,
  1. with open('OpenMe.mp3',"rb") as f1:
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-8-20 15:44:03 From FishC Mobile | 显示全部楼层
这是一个对象,不能用str强转
如果是纯文本文件,可以用list强转
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

发表于 2021-8-20 16:21:49 | 显示全部楼层    本楼为最佳答案   
本帖最后由 阿奇_o 于 2021-8-20 16:24 编辑

暂时你不需要明白,_io.TextIOWrapper
真要深究单看这文档https://docs.python.org/3/library/io.html#io.TextIOWrapper
也不完全能解答,因为前面还有个 _io.
所以,你只要知道它是个"对象",是个叫"TextIOWrapper"的对象,然后可以干嘛用的,就行。

其次,str(obj) 其实是 会调用对象obj的__str__方法,故结果是根据__str__方法的定制来的(自定义类里你可以随便怎么写),

  1. In [4]: with open('t.txt', 'r', encoding='utf-8') as f:
  2.    ...:     print(type(f))
  3.    ...:     print(f.__str__())
  4.    ...:
  5. <class '_io.TextIOWrapper'>
  6. <_io.TextIOWrapper name='t.txt' mode='r' encoding='utf-8'>

  7. >>> class Foo:
  8.         def __str__(self):
  9.                 return "我是 假的 <_io.TextIOWrapper name='t.txt' mode='r' ..>"


  10. >>> print(Foo)  # 类的
  11. <class '__main__.Foo'>
  12. >>> print(str(Foo()))   # 对象的 .__str__()
  13. 我是 假的 <_io.TextIOWrapper name='t.txt' mode='r' ..>
  14. >>> f = Foo()
  15. >>> print(f)
  16. 我是 假的 <_io.TextIOWrapper name='t.txt' mode='r' ..>
  17. >>>
  18. >>>
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-20 06:28

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表