我们已经知道了如何使用argv参数获取数据以及使用输入获取数据,现在我们开始学习从文件中获取数据。
这次读文件,需要我们编写两个文件,一个是执行脚本文件(ex8_1.py)一个是读取的文档文件(data.out),文档文件(data.out)的内容为:
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
然后,我们要通过open函数打开文档并且读取其中数据然后再在屏幕上输出数据,以下是读取文件的代码:
from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
得到的结果:
这里你可以看到,我们读入一个文件,读了两次,并且没有发现问题,这在有些语言里面是不允许的。这是python一条非常重要的性质