python如何读取文件数据_Python学习笔记之从文件中读取数据

10-1 Python 学习笔记:在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的Python 知识,其中每一行都以“In Python you can”打头。将这个文件命名为learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在with 代码块外打印它们。

新建文件learning_python.txt并添加如下内容

1 In Python you can Handle file2 In Python you can Automatic operation andmaintenance3 In Python you can make AI

编写python代码

1 filename='learning_python.txt'

2 with open(filename) as file_object:3 contents =file_object.read()4 print(contents.rstrip())5

6 print('')7

8 with open(filename) as file_object:9 for line infile_object:10 print(line.rstrip())11

12 print('')13

14 with open(filename) as file_object:15 lines =file_object.readlines()16for line inlines:17 print(line.rstrip())

执行结果

1 In Python you can Handle file2 In Python you can Automatic operation andmaintenance3 In Python you can make AI4

5 In Python you can Handle file6 In Python you can Automatic operation andmaintenance7 In Python you can make AI8

9 In Python you can Handle file10 In Python you can Automatic operation andmaintenance11 In Python you can make AI

总结:

with 在不需要访问文件后将其关闭

open()返回一个表示文件对象,python将这个文件对象储存到 file_object变量里

read()方法读取文件对象的全部内容,并将其作为一个长长的字符串存储在变量contents中

readlines()方法逐行读取文件对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值