標籤:
1. 模組匯入:
要使用一個模組,我們必須首先匯入該模組。Python使用import語句匯入一個模組。例如,匯入系統內建的模組 math:import math你可以認為math就是一個指向已匯入模組的變數,通過該變數,我們可以訪問math模組中所定義的所有公開的函數、變數和類:>>> math.pow(2, 0.5) # pow是函數1.4142135623730951>>> math.pi # pi是變數3.141592653589793如果我們只希望匯入用到的math模組的某幾個函數,而不是所有函數,可以用下面的語句:from math import pow, sin, log這樣,可以直接引用 pow, sin, log 這3個函數,但math的其他函數沒有匯入進來:>>> pow(2, 10)1024.0>>> sin(3.14)0.0015926529164868282如果遇到名字衝突怎麼辦?比如math模組有一個log函數,logging模組也有一個log函數,如果同時使用,如何解決名字衝突?如果使用import匯入模組名,由於必須通過模組名引用函數名,因此不存在衝突:import math, loggingprint math.log(10) # 調用的是math的log函數logging.log(10, ‘something‘) # 調用的是logging的log函數如果使用 from...import 匯入 log 函數,勢必引起衝突。這時,可以給函數起個“別名”來避免衝突:from math import logfrom logging import log as logger # logging的log現在變成了loggerprint log(10) # 調用的是math的loglogger(10, ‘import from logging‘) # 調用的是logging的log
question:
Python的os.path模組提供了 isdir() 和 isfile()函數,請匯入該模組,並調用函數判斷指定的目錄和檔案是否存在。注意: 1. 由於運行環境是平台伺服器,所以測試的也是伺服器中的檔案夾和檔案,該伺服器上有/data/webroot/resource/python檔案夾和/data/webroot/resource/python/test.txt檔案,大家可以測試下。2. 當然,大家可以在本機上測試是否存在相應的檔案夾和檔案。import osprint os.path.isdir(r‘C:\Windows‘)print os.path.isfile(r‘C:\Windows\notepad.exe‘)
answer:
from os.path import isdir,isfileprint isdir(r‘/data/webroot/resource/python‘)print isfile(r‘/data/webroot/resource/python/test.txt‘)
python 模組匯入