您好,欢迎来到筏尚旅游网。
搜索
您的当前位置:首页python读取文件内容

python读取文件内容

来源:筏尚旅游网

既然有了一个 File 对象,就可以开始从它读取内容。如果你希望将整个文件的内容读取为一个字符串值,就使用 File 对象的 read()方法。让我们继续使用保存在helloFile 中的 hello.txt File 对象。在交互式环境中输入以下代码:

>>> helloContent = helloFile.read()
>>> helloContent
'Hello world!'
When, in disgrace with fortune and men's eyes,
I all alone beweep my outcast state,
And trouble deaf heaven with my bootless cries,
And look upon myself and curse my fate,

确保用换行分开这 4 行。然后在交互式环境中输入以下代码:

>>> sonnetFile = open('sonnet29.txt')
>>> sonnetFile.readlines()
[When, in disgrace with fortune and men's eyes,\n', ' I all alone beweep my
outcast state,\n', And trouble deaf heaven with my bootless cries,\n', And
look upon myself and curse my fate,']

请注意,每个字符串值都以一个换行字符\n 结束。除了文件的最后一行。与单个大字符串相比,字符串的列表通常更容易处理。

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- efsc.cn 版权所有 赣ICP备2024042792号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务