在学习过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)