学习目标:
提示:我们之前也试用过 input 和 argv 获取用户输入,这次我们来试试读取文件。这个实验涉及2个文件,一个是正常的脚本文件,另一个是纯的文本文件,我们先看看文本文件内的内容:
# cat python07_test.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
我们这次做的实验就是用我们的脚本“打开”上述txt文件,然后将其打印出来。
学习实例:
from sys import argv
# filename可以替换成我们要打开的文件
script, filename = argv
# open属于函数,用来打开某些文件
txt = open(filename)
print(f"Here's your file {filename}:")
print(txt.read())
print("Type the filename again:")
file_again = input("> ")
txt_again = open(file_again)
print(txt_again.read())
·
代码的1-3行使用argv来获取文件名,之后会看到open这个新的函数命令,我们把这个与input命令类似。
· 我们在第8行又看到了新的内容,read函数。我们从open获得的东西是一个file(文件),文件本身也有一些你给它的命令。它接受命令的方式是使用句点( . ),紧跟着你的命令名,然后再跟着类似open和input的参数。不同的是:当我们执行txt.read()时,你的意思其实是:“txt!执行你的read命令,无须任何参数!”
之后执行,我们能看到结果如下:
# python python07.py python07_test.txt
Here's your file python07_test.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:
> python07_test.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
from sys import argv 这段话的意思:sys 是一个软件包,这句话的意思是从该软件包中取出argv这个特性。