1. 程式人生 > >模塊---常用模塊

模塊---常用模塊

列表 multi tdi atime nbsp 推出 python min 數字和字母

import os
print(os.getcwd()) #得到當前目錄
#os.chmod("/usr/local",7) #給文件或者文件夾加權限,7為最高權限
print(os.chdir("../")) #更改當前目錄
print(os.curdir) #當前目錄
print(os.pardir) #父目錄
print(os.mkdir("test1")) #創建文件夾
print(os.makedirs("usr/hehe/hehe1")) #遞歸創建文件夾,如果父目錄不存在則創建父目錄
#print(os.makdirs(r"usr/hehe/hehe1")) #遞歸創建文件夾,如果父目錄不存在則創建父目錄,r代表元字符的意思
print(os.removedirs("usr/hehe/hehe1")) #遞歸刪除空目錄
print(os.rmdir("usr/hehe/hehe1")) #刪除文件夾, 只能刪除空文件夾
print(os.remove("usr/hehe/hehe1")) #刪除文件
print(os.listdir(‘.‘)) #當前目錄下的所有文件列表
os.rename("test","test1")#重命名
print(os.stat("len_os.py"))#獲取文件信息
print(os.sep)#當前操作系統的路徑分隔符, windows的路徑分隔符為\,lnux的路徑分隔符為 /.
print(os.linesep)#當前操作系統的換行符
print(os.pathsep) # 當前系統的環境變量中每個路徑的分隔符,linux是:,windows是;
print(os.environ)#當前操作系統的環境變量
print(os.name)#當前系統名稱

print(os.path.abspath(__file__)) # 獲取絕對路徑,__file__表示當前文件
print(os.path.split("/usr/hehe/hehe.txt")) # 分割路徑和文件名

print(os.path.dirname("/usr/local")) # 獲取父目錄

print(os.path.basename("/usr/local")) # 獲取最後一級,如果是文件顯示文件名,如果是目錄顯示目錄名
print(os.path.exists("/usr/local")) # 判斷目錄/文件是否存在

print(os.path.isabs(".")) # 判斷是否是絕對路徑
print(os.path.isfile("/usr/local")) # 判斷是否是一個文件
print(os.path.isdir("/usr/local")) # 是否是一個路徑
print(os.path.join("/root", ‘hehe‘, ‘a.sql‘)) # 拼接成一個路徑
print(os.path.getatime("len_os.py")) # 輸出最近訪問時間
print(os.path.getmtime("len_os.py")) # 輸出最近訪問時間

import sys
sys.argv #獲取命令行參數List,第一個元素是程序本身路徑
sys.exit(n) #退出程序,正常退出時exit(0),若exit(‘xxxxx),則推出並返回xxxxx
sys.version #獲取Python解釋程序的版本信息
sys.maxint #當前操作系統支持最大的Int值,32位和64位不同
sys.path #返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值
sys.platform #返回操作系統平臺名稱
sys.stdout.write(‘please:‘) # 向屏幕輸出一句話
val = sys.stdin.readline()[:-1] # 獲取輸入的值

import random, string

print(random.random()) # 隨機浮點數,默認取0-1,不能指定範圍
print(random.randint(1, 20)) # 隨機整數,1-20
print(random.randrange(1, 20)) # 隨機產生一個整數,1-19,它是顧頭不顧尾的
print(random.choice(‘x23serw4‘)) # 隨機取一個元素
print(random.sample(‘hello‘, 2)) # 從序列中隨機取幾個元素
print(random.uniform(1, 9)) # 隨機取浮點數,可以指定範圍
x = [1, 2, 3, 4, 6, 7]
random.shuffle(x) # 洗牌,打亂順序,會改變原list的值
print(x)
print(string.ascii_letters + string.digits) # 所有的數字和字母

import datetime, time

print(time.timezone) # 和標準時間相差的時間,單位是s
print(time.time()) # 獲取當前時間戳,即從linux元年到現在的秒數, 常用格式為int(time.time()),取整
print(time.sleep(1)) # 休息幾s

print(time.gmtime()) # 把時間戳轉換成時間元組,如果不傳的話,默認取標準時區的時間戳
print(time.localtime()) # 把時間戳轉換成時間元組,如果不傳的話,默認取當前時區的時間戳
print(time.mktime(time.localtime())) # 把時間元組轉換成時間戳

print(time.strftime("%y%m%d %H%M%S")) # 將時間元組轉換成格式化輸出的字符串
print(time.strptime("20160204 191919", "%Y%m%d %H%M%S")) # 將格式化的時間轉換成時間元組

print(time.struct_time) # 時間元組
print(time.asctime()) # 時間元轉換成格式化時間
print(time.ctime()) # 時間戳轉換成格式化時間
print(datetime.datetime.now()) # 當然時間格式化輸出
print(datetime.datetime.now() + datetime.timedelta(3)) # 3天後的時間
print(datetime.datetime.now() + datetime.timedelta(-3)) # 3天前的時間

import json

dic = {"name": "niuniu", "age": 18}
print(json.dumps(dic)) # 把字典轉成json串
fj = open(‘a.json‘, ‘w‘)
print(json.dump(dic, fj)) # 把字典轉換成的json串寫到一個文件裏面
s_json = ‘{"name":"niuniu","age":20,"status":true}‘
print(json.loads(s_json)) # 把json串轉換成字典
fr = open(‘b.json‘, ‘r‘)
print(json.load(fr)) # 從文件中讀取json數據,然後轉成字典

import hashlib

m = hashlib.md5()
m.update(b"Hello")
m.update(b"It‘s me")
print(m.digest())
m.update(b"It‘s been a long time since last time we ...")

print(m.digest()) # 2進制格式hash
print(len(m.hexdigest()))  # 16進制格式hash
# ######## md5 ########



hash = hashlib.md5()
hash.update(‘admin‘)
print(hash.hexdigest())
# ######## sha1 ########

hash = hashlib.sha1()
hash.update(‘admin‘)
print(hash.hexdigest())
# ######## sha256 ########

hash = hashlib.sha256()
hash.update(‘admin‘)
print(hash.hexdigest())

# ######## sha384 ########

hash = hashlib.sha384()
hash.update(‘admin‘)
print(hash.hexdigest())
# ######## sha512 ########

hash = hashlib.sha512()
hash.update(‘admin‘)
print(hash.hexdigest())


import shelve
d = shelve.open(‘shelve_test‘) #打開一個文件
class Test(object):
def __init__(self,n):
self.n = n
t = Test(123)
t2 = Test(123334)
def func():
print(‘hello‘)
name = ["alex","rain","test"]
d["test"] = name #持久化列表
d["t1"] = t #持久化類
d["t2"] = t2
d["t3"] = func
print(d.get("t3"))#獲取內容
d.close()

import configparser

config = 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‘ # mutates the parser
topsecret[‘ForwardX11‘] = ‘no‘ # same here
config[‘DEFAULT‘][‘ForwardX11‘] = ‘yes‘
with open(‘example.ini‘, ‘w‘) as configfile:
config.write(configfile)

import configparser


config = configparser.ConfigParser()
config.read(‘my.cnf‘)
sections = config.sections() # 獲取所有節點
print(config.get(‘bitbucket.org‘, ‘User‘)) # 取對應節點下面key的值
config.add_section(‘NEW‘) # 增加節點
config.set(‘NEW‘, ‘test‘, ‘true‘) # 增加節點下面對應的熟悉和值
config.set(‘DEFAULT‘, ‘niu‘, ‘222222‘) # 修改節點下的屬性
config.write(open("my.cnf", "w")) # 寫入修改後的文件
config.has_option(‘NEW‘, ‘test‘) # 節點下是否有對應的屬性
config.has_section(‘NEW‘) # 是否有該節點
config.remove_section(‘NEW‘) # 刪除節點
config.remove_option(‘NEW‘, ‘test‘) # 刪除節點下面的key

‘‘‘
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
‘‘‘

re.match #從頭開始匹配
re.search #匹配包含
re.findall #把所有匹配到的字符放到以列表中的元素返回
re.splitall #以匹配到的字符當做列表分隔符
re.sub #匹配字符並替換


if __name__=‘__main__‘: # 只有在運行自己這個Python文件的時候,才會執行下面的代碼,在別的模塊裏面導入的時候是不會執行的
__mokuai__
 

模塊---常用模塊