1、新建一个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.2、ex15.py
from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
txt.close()
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
txt_again.close()
学习要点:
1、filename和file_again是前面学过的,通过两种不同的方式获取文件名
2、open()函数,返回file object
可以用命令python -m pydoc open查看
非windows试下pydoc open
3、file object.read()把文件的内容当成字符串返回。
4、file object.close()关闭文件,这点很重要
可以用命令python -m pydoc file
然后找到read和close方法的帮助