小技巧:ALT+3可多行注釋ALT+4多行取消注釋,F5運行,cmd下直接輸入python -m pydoc 即可開啟協助文檔,或者可直接在後面加上函數就可查詢用法如python -m pydoc round
1 %r
百分比符號非常規用法:
formatter = "%r %r %r %r"
print formatter % (1, 2, 3, 4)
將 %r 和 %s 比較一下。注意到了嗎。%r 列印出來的是你寫在指令碼裡的內容,而 %s 列印的是你應該看到的內容
2 input()
python3中沒有raw_input()函數了,直接用input()代替
可在括弧中加提示,如:age=input('age?')
3 參數,解包(ex13)
from sys import argv
a,b,c,d = argv
print('1',a)
print('2',b)
print('3',c)
print('4',d)
之後在命令提示字元裡開啟用 >>>python 1.py first 2nd 3rd #要理解到1.py實際也是個參數
這樣就可以“把 argv 中的東西解包,將所有的參數依次賦予左邊的變數名”
4 讀取檔案(ex15)
from sys import argv #調用sys的argv
script,filename= argv #用argv擷取檔案名稱,script,filename只是變數名隨便起的不影響
txt=open(filename )#開啟輸入的第二個參數對應檔案
print ('here is your file %r.' %filename) #讀取第二個參數對應檔案的名字
print(txt.read()) #顯示第二個參數對應檔案的內容
print('type the filename again:') #進行第二種開啟檔案的方法
file_again=input('>') #讓輸入要開啟檔案的名字
txt_again=open(file_again )#開啟
print (txt_again.read())
在命令列輸入>>>python 1.py ex15_sample.txt #輸入兩個參數,分別替代script,filename
5 應該記 住的命令如下:
• close – 關閉檔案。跟你編輯器的 檔案 -> 儲存.. 一個意思。
• read – 讀取檔案內容。你可以把結果賦給一個變數。
• readline – 讀取文字檔中的一行。
• truncate – 清空檔案,請小心使用該命令。
• write(stuff) – 將 stuff 寫入檔案。
6 寫檔案
from sys import argv
script,filename= argv#用argv擷取檔案名稱
print ('wo are going to erase %r.' %filename)
print('if you don\'t want that,hit CTRL-C(^C).')
print('if you do want that,hit RETURN')
input('?')
print('opening the file...')
target=open(filename,'w')#寫入模式
print('Good bye!')
target.truncate()#清除內容
###前半段是擦除之前的資料,後半段是寫資料
print ('now i am going to ask 3 lines')
line1=input('line1:')##此處引號不能去掉,因為並沒有定義line1
line2=input('line2:')
line3=input('line3:')
print('i am going to write these to the file.')
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
#######此處也可用target.write(line1 + '\n' + line2 + '\n' + line3)代替,注意write()只能是一個字串。如果多個字串,使用print()可以使用逗號分隔,而使用######write()只能把各字串相加
print ('And finally, we close it.')
target.close()
7 檔案模式
預設的檔案開啟後,是返回一個唯讀檔案,如果你想寫在檔案中的話,必須顯示的定義mode參數,下面是mode參數最經常使用的值 Value Description 'r' Read mode 'w' Write mode 'a' Append mode 'b' Binary mode (added to other mode) '+' Read/write mode(added to other mode) 其中’+‘可以添加在任何一個模式後面,表示可讀可寫 ‘b’用來改變不同的檔案處理方式,b表示binary,像視頻,映像等等資訊就是一個二進位檔案,可以讀的時候加上'rb'模式,這個表示以二進位的形式讀取檔案
8 ex17
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print('copy from %s to %s'%(from_file, to_file))
input=open(from_file)
indata=input.read()
print('the input file is %d bytes long'%len(indata))
print('does the output ile exist? %r'%exists(to_file))
print('ready,hit RETURN to continue,CTRL-C to abort.')
input()
output=open(to_file,'w')
output.write(indata)
print('All right!')
output.close()
input.close()
##########不知道哪裡出錯了,提示的‘typeerror '_io.textiowrapper' object is not callable’