python進階(1)——模組:開箱即用
阿新 • • 發佈:2018-11-10
一.開箱即用
之前總結的將模組作為函式匯入程式中:https://mp.csdn.net/postedit/80904368
二.查明模組包含什麼:dir()
dir(copy)
使用help獲取幫助
help(copy)
help(copy.copy)
help(copy.copy.__doc__)
閱讀模組的原始碼,查詢路徑(注意不要對檔案進行修改)
print(copy.__file__)
/anaconda3/lib/python3.6/copy.py
三. 常用的模組
1 sys模組
argv,path,modules,,,
sys.argv[]:從程式外部獲取引數
當[]中為0時,
import sys
args=sys.argv[0]
print(' '.join(args))
輸出:
/ U s e r s / c c d e m a c b o o k a i r / D e s k t o p / l c c t r y . p y
當[]中為1時,
import sys
args=sys.argv[1]
print(' '.join(args))
當[]中為1:時
import sys args=sys.argv[1:] args.reverse() print(' '.join(args))
2 os模組
os.system用於執行外部程式
就啟動web瀏覽器而言,使用webbrowser模組更佳
import webbrowser
webbrowser.open('http://www.python.org')
3 fileinput模組(迭代一系列文字檔案中的所有行)
例1:以註釋的方式給程式碼行的末尾加上行號,要求:
import fileinput for line in fileinput.input(inplace=True): #將input的引數inplace設定為True,將就地進行處理 line = line.rstrip() #rstrip將字串末尾所有的chars字元都刪除並返回結果 num = fileinput.lineno() #lineo返回在當前檔案中的行號 print('{:<50} # {:2d}'.format(line,num))
執行:python lcctry.py lcctry.py
結果將對程式重新進行列印並輸出
注:{:<50}表示把程式碼行line在50個寬度的位置靠左對齊,然後新增#num,num取2個寬度的十進位制數顯示,
慎用引數inplace!!確保程式正確後再讓它修改檔案
3 re——正則表示式(專門下一節討論)