python 筆記 argv、open(filename)和.read()——12.25
習題 13: 引數、解包、變數
大體來說就是寫個接受引數的指令碼
argv 是所謂的“引數變數 (argument variable)”,是一個非常標準的程式設計術語。在其他的程式語言裡你
也可以看到它。這個變數包含了你傳遞給 Python 的引數。
ex11.py
#-*- coding:utf-8-*-
from sys import argv #其實就是允許使用argv這個內建變數,而import就是模組(modules)
script, first, second, third = argv
#解包,script是指令碼(xxx.py)檔名
#first, second, third分別是第1,2,3個命令列引數
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:",third
執行結果:
感悟與自我測試:
raw_input()與argv的區別:使用的時機不同,由以上例子可以看出,
argv是在在使用者執行時候使用的。
raw_input()則是在使用中使用的。
以下進行合併測試:
ex13_1.py
#-*- coding:utf-8-*-
from
script, first, second, third, fourth = argv
print "The script is called:",script
print "The first dog is called:", first
print "The second dog is called:", second
print "The third dog is called:", third
print "The fourth dog is called:", fourth
name =raw_input("What's you name?")
print "Oh, %r, your are so good!" %name
執行結果:
習題 14: 提示和傳遞
目標:
v 和 raw_input,為如何讀寫檔案做基礎
ex14.py
# -*- coding: utf-8-*-
from sys import argv
script,user_name = argv #此處只定義一個,所以之後需要跟一個命令引數
prompt = '>'
prompt1 = '>>>>'
print "Hi %s, I'm the %s script." %(user_name, script)
#此處也很好理解,一個是我們跟的命令引數,
#一個是這個指令碼的名稱,此處為ex14.py
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
likes = raw_input(prompt)
print "Where do you live %s?" %user_name
lives = raw_input(prompt1)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print """
Alright, so you said %r about likingme.
You live in %r. Not sure where thatis.
And you have a %r computer. Nice.
""" %(likes , lives, computer)
執行結果:
習題 15: 讀取檔案
目標與感悟:
熟練使用 |
arg |
學習使用 |
open(filename) |
.read() |
sys |
是一個程式碼庫,from sys import argv是從sys程式碼庫中提取內建的argv,所以後續無需再定義argv |
ex15.py
# -*- coding:utf-8-*-
from sys import argv
script, filename = argv
txt = open(filename) #txt表示動作,開啟filename
print "Here'syour file %r:" %filename #列印所跟的命令引數
print txt.read() #理解為固定用法,讀取txt的內容
print "Typethe filename again:" #詢問是否再一次讀取
file_again = raw_input(">") #用>來引導輸入,將輸入的結果定義給file_again
txt_again = open(file_again) #將開啟輸入結果檔案的動作定義給txt_again
printtxt_again.read() #列印讀取txt_again的內容
ex15_sample.txt
This is stuff Ityped into a file.
It is really coolstuff.
Lots and lots of funto have in here.
執行結果: