笨办法学python习题15 读取文件

在学习过raw_input和argv后是学习读取文件的必要基础!

首先,开始学习这个习题之前,需要首先准备2个文件:1,ex15.py  2,ex15_sample.txt

学习的成果是利用Terminal打印出ex15_sample.txt中写入的内容。

首先,放上学习代码

#-*-coding:utf-8-*-
from sys import argv     #从sys模块导入argv对象

script , filename = argv #将argv对象解包并赋值给script 和 filename变量

txt = open(filename)     #open函数接受一个filename的参数,同时返回一个文件对象,并赋值给txt

print "Here's your file %r:" %filename  #打印filename的名字
print txt.read()         #txt当前是一个对象,txt.read()那么read是txt的方法(类似VBA对象的属性和方法)

print"Type the filename again:" #提示输入filename
file_again = raw_input(">")     #打印提示符

txt_again = open(file_again)    #相同的方法打开file_again参数,返回一个文件对象给txt_again

print txt_again.read()          #txt_again的read方法读取文件内容并打印出来

运行结果:(黄色mark部分为再次输入的部分)

mystuff simengred$ python ex15.py ex15_sample.txt
Here's your file 'ex15_sample.txt':
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
Type the filename again:
>ex15_sample.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
这个习题的知识点:

1,通过在Terminal中输入pydoc open得到以下信息:

open(...)

    open(name[, mode[, buffering]]) -> file object

    Open a file using the file() type, returns a file object.

说明Open函数在接受一个参数后,返回了一个file的对象
2,对象.方法的运用

txt = open(filename),open返回的对象赋值给了txt。

txt.read()就是一个对象的方法(Method)


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值