python基礎學習04

來源:互聯網
上載者:User

標籤:imp   ftime   檔案內容   rand   count   ssi   hive   basename   leo   

模組定義:用來從邏輯上組織python代碼(變數,函數,類,邏輯),本質就是.py結尾的python檔案,實現一個功能
包定義:用來從邏輯上組織模組的,本質就是一個目錄,必須帶有__init__.py檔案
匯入:import module_name1,module_name2 from package_name 或 module_name import *
from package_name 或 module_name import func as func_name
import模組本質:匯入模組的本質就是把python檔案解釋一遍
import包本質:匯入包的本質就是執行該包下的__init__.py檔案
import包時,可以在__init__.py檔案中,匯入該包內的模組(from . import module_name),這樣,匯入包時,就可以調用該包下的其它模組
模組的分類:
1)標準庫
2)開源模組
3)自訂模組


# 時間模組 time與datetime
import time

# 從1970-01-01 00:00:00到當前的秒數 時間戳記
print(time.time())
# 本地時間 結構化的時間 可以傳時間戳記
print(time.localtime())
# 休眠
time.sleep(1)
# 將時間戳記轉換成UTC標準時間的結構化時間
print(time.gmtime(time.time()))
# 將結構化的時間轉換成時間戳記
print(time.mktime(time.localtime()))
# 將結構化時間轉換成字串
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
# 將字串轉化成結構化時間
print(time.strptime(‘2016-08-20 14:31:52‘, ‘%Y-%m-%d %H:%M:%S‘))
# 將結構化時間轉換成英文字串,可接收元組
print(time.asctime())
# 將結構化時間轉換成英文字串,可接收時間戳記
print(time.ctime())


import datetime

# 擷取目前時間
print(datetime.datetime.now())
# 時間計算,不能單獨使用
print(datetime.datetime.now()+datetime.timedelta(-3))
print(datetime.datetime.now()+datetime.timedelta(hours=-3))


# 隨機模組
import random

# 隨機0-1浮點數
print(random.random())
# 隨機1-3整數
print(random.randint(1, 3))
# 隨機0-2整數
print(random.randrange(1, 3))
# 在序列類型中隨機取值
print(random.choice(‘hello‘))
print(random.choice([1, 2, 3, 4]))
# 在序列類型中隨機取2位
print(random.sample(‘hello‘, 2))
# 隨機區間內浮點數
print(random.uniform(2, 3))
# 將有序列表隨機打亂
i = [1, 2, 3, 4]
random.shuffle(i)
print(i)


os模組

# 擷取目前的目錄
print(os.getcwd())
# 切換目錄
os.chdir("/home")
print(os.getcwd())
# 返回目前的目錄
print(os.curdir)
# 返回上一級目錄
print(os.pardir)
# 遞迴建立目錄os.makedirs(os.path.dirname(os.path.abspath(__file__)) + "/a/b/c")# 遞迴刪除目錄 若目錄為空白,則刪除,並遞迴到上一級目錄,如若也為空白,則刪除,依此類推os.removedirs(os.path.dirname(os.path.abspath(__file__)) + "/a/b/c")# 建立目錄os.mkdir(os.path.dirname(os.path.abspath(__file__)) + "/a")# 刪除空目錄os.rmdir(os.path.dirname(os.path.abspath(__file__)) + "/a")# 顯示目錄內容print(os.listdir("."))# 重新命名os.rename(os.path.dirname(os.path.abspath(__file__)) + "/a", os.path.dirname(os.path.abspath(__file__)) + "/b")# 擷取檔案資訊print(os.stat("b/123"))# 輸出作業系統特定的路徑分隔字元print(os.sep)# 輸出當前作業系統分行符號print(os.linesep)# 輸出用於分隔檔案路徑的字串print(os.pathsep)# 輸出環境變數print(os.environ)# 輸出當前系統平台print(os.name)# 執行系統命令os.system("dir")# 擷取當前檔案的絕對路徑print(os.path.abspath(__file__))# 將path分割目錄和檔案名稱print(os.path.split(os.path.dirname(os.path.abspath(__file__)) + "/b/123"))# 返回path的目錄print(os.path.dirname(os.path.dirname(os.path.abspath(__file__)) + "/b/123"))# 返回path目錄中的檔案名稱print(os.path.basename(os.path.dirname(os.path.abspath(__file__)) + "/b/123"))# 判斷路徑是否存在print(os.path.exists(os.path.dirname(os.path.abspath(__file__)) + "/b/123"))# 判斷是否是絕對路徑print(os.path.isabs("home"))# 判斷是否是檔案print(os.path.isfile("b/123"))# 將多個路徑組合并返回,第一個絕對路徑之前的參數將被忽略print(os.path.join(‘/home‘, ‘a.txt‘))# 擷取檔案或目錄的最後存取時間print(os.path.getatime(os.path.dirname(os.path.abspath(__file__))))# 擷取檔案或目錄的最後修改時間print(os.path.getatime(os.path.dirname(os.path.abspath(__file__))))shutil模組http://www.cnblogs.com/wupeiqi/articles/4963027.html# 將檔案內容拷貝到另一個檔案中,可以部分內容f1 = open(‘123‘, encoding=‘utf-8‘)f2 = open(‘1234‘, ‘w‘, encoding=‘utf-8‘)shutil.copyfileobj(f1, f2)# 拷貝檔案shutil.copyfile(‘123‘, ‘1234‘)# 僅拷貝許可權.內容,組,使用者均不變shutil.copymode(‘123‘, ‘1234‘)# 拷貝狀態的資訊,包括:mode bits,atime,mtime,falgsshutil.copystat(‘123‘, ‘1234‘)# 拷貝檔案和許可權shutil.copy(‘123‘, ‘12345‘)# 拷貝檔案和狀態資訊shutil.copy2(‘123‘, ‘123456‘)# 遞迴的去拷貝檔案shutil.copytree(os.path.dirname(os.path.abspath(__file__)), os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+"/新模組")# 遞迴刪除目錄shutil.rmtree(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+"/新模組")# 遞迴移動檔案shutil.copytree(os.path.dirname(os.path.abspath(__file__)), os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+"/新模組")# 建立壓縮包並返迴文件路徑,例如:zip,tar# base_name:壓縮包的檔案名稱,也可以是壓縮包的路徑.只是檔案名稱時,則儲存至目前的目錄,否則儲存至指定路徑,# 如:www =>儲存至當前路徑# 如:/user/wupeiqi/www =>儲存至/user/wupeiqi/ www是包名# format:壓縮包種類,"zip","tar","bztar","gztar"# root_dir:要壓縮的檔案夾路徑(預設目前的目錄)# owner:使用者,預設目前使用者# group:組,預設當前組# logger:用於記錄日誌,通常是logging.Logger對象# 注:壓縮路徑不要包含程式所在的路徑,不然會將自已再壓縮一層shutil.make_archive(‘abc‘, "zip", os.path.dirname(os.path.dirname(os.path.abspath(__file__))))# shelve模組是一個簡單的K,V將內在資料通過檔案持久化的模組,可以持久化任何pickle可支援的python資料格式import datetimeimport shelvewith shelve.open(‘shelve_test‘) as d: info = { ‘age‘: 20, "job": ‘it‘ } name = [‘alex‘, ‘rain‘, ‘test‘] d[‘name‘] = name d[‘info‘] = info d["date"] = datetime.datetime.now()d = shelve.open(‘shelve_test‘)print(d.get(name))print(d.get("info"))print(d.get("date"))PyYAML模組http://pyyaml.org/wiki/PyYAMLDocumentationConfigParser模組 用於產生和修改常見配置文檔,當前模組的名稱在python3中變更為configparser# 寫檔案import configparserconfig = configparser.ConfigParser()config["DEFAULT"] = { ‘ServerAliveInterval‘: ‘45‘, ‘Compression‘: ‘yes‘, ‘CompressionLevel‘: ‘9‘}config[‘bitbucket.org‘] = {}config[‘bitbucket.org‘][‘User‘] = ‘hg‘config[‘topsecret.server.com‘] = {}topsecret = config[‘topsecret.server.com‘]topsecret[‘Host Port‘] = ‘50022‘topsecret[‘ForwardX11‘] = ‘no‘config[‘DEFAULT‘][‘ForwardX11‘] = ‘yes‘with open(‘example.ini‘, ‘w‘) as configfile: config.write(configfile)# 讀檔案import configparserconfig = configparser.ConfigParser()config.read(‘example.ini‘)# 取除default以外的所有節點print(config.sections())# 取default的內容print(config.defaults())# 取節點內容print(config[‘bitbucket.org‘][‘user‘])# 刪除節點config.remove_section(‘bitbucket.org‘)config.write(open(‘example1.ini‘, ‘w‘))# hashlib模組 用於加密相關的操作,3.x裡代替了md5模組和sha模組,主要提供SHA1,SHA224,SHA256,SHA384,SHA512,MD5演算法import hashlibm = hashlib.md5()m.update(‘天王蓋地虎‘.encode(encoding=‘utf-8‘))# 十進位加密print(m.digest())# 十六進位加密print(m.hexdigest())s = hashlib.sha1()s.update(b‘Hello‘)print(s.digest())print(s.hexdigest())# 比較常用s1 = hashlib.sha256()s1.update(b‘Hello‘)print(s1.digest())print(s1.hexdigest())# hmac 用於訊息加密import hmach = hmac.new(b‘12345‘, ‘天王蓋地虎‘.encode(encoding=‘utf-8‘))print(h.digest())print(h.hexdigest())re模組‘.‘ 預設匹配除\n之外的任意一個字元,若指定flag DOTALL, 則匹配任一字元,包括換行‘^‘ 匹配字元開頭,若指定flags MULTILINE, 這種也可以匹配上(r"^a", "\nabc\neee", flags=re.MULTILINE)‘$‘ 匹配字元結尾,或e.search("foo$", "bfoo\nsdfsf", flags=re.MULTILINE).group()也可以‘*‘ 匹配 * 號前的字元0次或多次,re.findall("ab*", "cabb3abcbbac")結果為[‘abb‘, ‘ab‘, ‘a‘]‘+‘ 匹配前一個字元1次或多次,re.findall("ab+", "ab+cd+abb+bba")結果[‘ab‘, ‘abb‘]‘?‘ 匹配前一個字元1次或0次‘{m}‘ 匹配前一個字元m次‘{n,m}‘ 匹配前一個字元n到m次,re.findall("ab{1,3}", "abb abc abbcbbb")結果‘abb‘, ‘ab‘, ‘abb‘]‘|‘ 匹配 | 左或 | 右的字元,re.search("abc|ABC", "ABCBabcCD").group()結果‘ABC‘‘(...)‘ 分組匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group()結果abcabca456c‘\A‘ 只從字元開頭匹配,re.search("\Aabc", "alexabc")是匹配不到的‘\Z‘ 匹配字元結尾,同$‘\d‘ 匹配數字0 - 9‘\D‘ 匹配非數字‘\w‘ 匹配[A - Za - z0 - 9]‘\W‘ 匹配非[A - Za - z0 - 9]‘\s‘ 匹配空白字元、\t、\n、\r, re.search("\s+", "ab\tc1\n3").group()結果‘\t‘‘(?P<name>...)‘ 分組匹配re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})", "371481199306143242").groupdict("city")結果{‘province‘: ‘3714‘, ‘city‘: ‘81‘, ‘birthday‘: ‘1993‘}import reres = re.match(‘^abc\d+‘, ‘abc321jbakk333‘)res = re.match(‘a.+k‘, ‘abc321jbakk333‘)res = re.search(‘c.+k‘, ‘abc321jbakk333‘)res = re.search(‘j[a-zA-Z]+k‘, ‘abc321jbAakk333‘)print(res.group())res = re.findall(‘[0-9]{1,3}‘, ‘aa1x2k345kkd‘)print(res)res = re.search(‘(?P<id>[0-9]+)(?P<name>[a-zA-z]+)‘, ‘[email protected]‘).groupdict()print(res)res = re.split(‘[0-9]+‘, ‘abc12de3f45GH‘)print(res)res = re.sub(‘[0-9]+‘, ‘|‘, ‘abc12de3f45GH‘, count=2)print(res)res = re.search(‘\\\\‘, ‘akdbsk\kdiek‘)print(res.group())# 忽略大小寫res = re.search(‘[a-z]+‘, ‘akdbskA‘, flags=re.I)print(res.group())

python基礎學習04

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.