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 sys import argv

 

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.

 

 

運行結果:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章