模塊,用一砣代碼實現了某個功能的代碼集合。
類似於函數式編程和麪向過程編程,函數式編程則完成一個功能,其他代碼用來調用即可,提供了代碼的重用性和代碼間的耦合。而對於一個複雜的功能來,可能需要多個函數才能完成(函數又可以在不同的.py文件中),n個 .py 文件組成的代碼集合就稱爲模塊。
如:os 是系統相關的模塊;file是文件操作相關的模塊
模塊分爲三種:
1、定義模塊
情景一:
情景二:
情景三:
2、導入模塊
Python之所以應用越來越廣泛,在一定程度上也依賴於其爲程序員提供了大量的模塊以供使用,如果想要使用模塊,則需要導入。導入模塊有一下幾種方法:
1
2
3
4
|
import
module
from
module.xx.xx
import
xx
from
module.xx.xx
import
xx as rename
from
module.xx.xx
import
*
|
導入模塊其實就是告訴Python解釋器去解釋那個py文件
那麼問題來了,導入模塊時是根據那個路徑作爲基準來進行的呢?即:sys.path
1
2
3
4
5
|
import
sys
print
sys.path
結果:
[
'/Users/wupeiqi/PycharmProjects/calculator/p1/pp1'
,
'/usr/local/lib/python2.7/site-packages/setuptools-15.2-py2.7.egg'
,
'/usr/local/lib/python2.7/site-packages/distribute-0.6.28-py2.7.egg'
,
'/usr/local/lib/python2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.10-x86_64.egg'
,
'/usr/local/lib/python2.7/site-packages/xlutils-1.7.1-py2.7.egg'
,
'/usr/local/lib/python2.7/site-packages/xlwt-1.0.0-py2.7.egg'
,
'/usr/local/lib/python2.7/site-packages/xlrd-0.9.3-py2.7.egg'
,
'/usr/local/lib/python2.7/site-packages/tornado-4.1-py2.7-macosx-10.10-x86_64.egg'
,
'/usr/local/lib/python2.7/site-packages/backports.ssl_match_hostname-3.4.0.2-py2.7.egg'
,
'/usr/local/lib/python2.7/site-packages/certifi-2015.4.28-py2.7.egg'
,
'/usr/local/lib/python2.7/site-packages/pyOpenSSL-0.15.1-py2.7.egg'
,
'/usr/local/lib/python2.7/site-packages/six-1.9.0-py2.7.egg'
,
'/usr/local/lib/python2.7/site-packages/cryptography-0.9.1-py2.7-macosx-10.10-x86_64.egg'
,
'/usr/local/lib/python2.7/site-packages/cffi-1.1.1-py2.7-macosx-10.10-x86_64.egg'
,
'/usr/local/lib/python2.7/site-packages/ipaddress-1.0.7-py2.7.egg'
,
'/usr/local/lib/python2.7/site-packages/enum34-1.0.4-py2.7.egg'
,
'/usr/local/lib/python2.7/site-packages/pyasn1-0.1.7-py2.7.egg'
,
'/usr/local/lib/python2.7/site-packages/idna-2.0-py2.7.egg'
,
'/usr/local/lib/python2.7/site-packages/pycparser-2.13-py2.7.egg'
,
'/usr/local/lib/python2.7/site-packages/Django-1.7.8-py2.7.egg'
,
'/usr/local/lib/python2.7/site-packages/paramiko-1.10.1-py2.7.egg'
,
'/usr/local/lib/python2.7/site-packages/gevent-1.0.2-py2.7-macosx-10.10-x86_64.egg'
,
'/usr/local/lib/python2.7/site-packages/greenlet-0.4.7-py2.7-macosx-10.10-x86_64.egg'
,
'/Users/wupeiqi/PycharmProjects/calculator'
,
'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python27.zip'
,
'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7'
,
'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin'
,
'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac'
,
'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages'
,
'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk'
,
'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old'
,
'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload'
,
'/usr/local/lib/python2.7/site-packages'
,
'/Library/Python/2.7/site-packages'
]
|
如果sys.path路徑列表沒有你想要的路徑,可以通過 sys.path.append('路徑') 添加。
1
2
3
4
|
import
sys
import
os
project_path
=
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(project_path)
|
內置模塊是Python自帶的功能,在使用內置模塊相應的功能時,需要【先導入】再【使用】
用於提供對Python解釋器相關的操作:
1
2
3
4
5
6
7
8
9
|
sys.argv 命令行參數
List
,第一個元素是程序本身路徑
sys.exit(n) 退出程序,正常退出時exit(
0
)
sys.version 獲取Python解釋程序的版本信息
sys.maxint 最大的
Int
值
sys.path 返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值
sys.platform 返回操作系統平臺名稱
sys.stdin 輸入相關
sys.stdout 輸出相關
sys.stderror 錯誤相關
|
用於提供系統級別的操作:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
os.getcwd() 獲取當前工作目錄,即當前python腳本工作的目錄路徑
os.chdir(
"dirname"
) 改變當前腳本工作目錄;相當於shell下cd
os.curdir 返回當前目錄: (
'.'
)
os.pardir 獲取當前目錄的父目錄字符串名:(
'..'
)
os.makedirs(
'dir1/dir2'
) 可生成多層遞歸目錄
os.removedirs(
'dirname1'
) 若目錄爲空,則刪除,並遞歸到上一級目錄,如若也爲空,則刪除,依此類推
os.mkdir(
'dirname'
) 生成單級目錄;相當於shell中mkdir dirname
os.rmdir(
'dirname'
) 刪除單級空目錄,若目錄不爲空則無法刪除,報錯;相當於shell中rmdir dirname
os.listdir(
'dirname'
) 列出指定目錄下的所有文件和子目錄,包括隱藏文件,並以列表方式打印
os.remove() 刪除一個文件
os.rename(
"oldname"
,
"new"
) 重命名文件
/
目錄
os.stat(
'path/filename'
) 獲取文件
/
目錄信息
os.sep 操作系統特定的路徑分隔符,win下爲
"\\",Linux下爲"
/
"
os.linesep 當前平臺使用的行終止符,win下爲
"\t\n"
,Linux下爲
"\n"
os.pathsep 用於分割文件路徑的字符串
os.name 字符串指示當前使用平臺。win
-
>
'nt'
; Linux
-
>
'posix'
os.system(
"bash command"
) 運行shell命令,直接顯示
os.environ 獲取系統環境變量
os.path.abspath(path) 返回path規範化的絕對路徑
os.path.split(path) 將path分割成目錄和文件名二元組返回
os.path.dirname(path) 返回path的目錄。其實就是os.path.split(path)的第一個元素
os.path.basename(path) 返回path最後的文件名。如何path以/或\結尾,那麼就會返回空值。即os.path.split(path)的第二個元素
os.path.exists(path) 如果path存在,返回
True
;如果path不存在,返回
False
os.path.isabs(path) 如果path是絕對路徑,返回
True
os.path.isfile(path) 如果path是一個存在的文件,返回
True
。否則返回
False
os.path.isdir(path) 如果path是一個存在的目錄,則返回
True
。否則返回
False
os.path.join(path1[, path2[, ...]]) 將多個路徑組合後返回,第一個絕對路徑之前的參數將被忽略
os.path.getatime(path) 返回path所指向的文件或者目錄的最後存取時間
os.path.getmtime(path) 返回path所指向的文件或者目錄的最後修改時間
|
用於加密相關的操作,代替了md5模塊和sha模塊,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
import
hashlib
# ######## md5 ########
hash
=
hashlib.md5()
# help(hash.update)
hash
.update(bytes(
'admin'
, encoding
=
'utf-8'
))
print
(
hash
.hexdigest())
print
(
hash
.digest())
######## sha1 ########
hash
=
hashlib.sha1()
hash
.update(bytes(
'admin'
, encoding
=
'utf-8'
))
print
(
hash
.hexdigest())
# ######## sha256 ########
hash
=
hashlib.sha256()
hash
.update(bytes(
'admin'
, encoding
=
'utf-8'
))
print
(
hash
.hexdigest())
# ######## sha384 ########
hash
=
hashlib.sha384()
hash
.update(bytes(
'admin'
, encoding
=
'utf-8'
))
print
(
hash
.hexdigest())
# ######## sha512 ########
hash
=
hashlib.sha512()
hash
.update(bytes(
'admin'
, encoding
=
'utf-8'
))
print
(
hash
.hexdigest())
|
以上加密算法雖然依然非常厲害,但時候存在缺陷,即:通過撞庫可以反解。所以,有必要對加密算法中添加自定義key再來做加密。
1
2
3
4
5
6
7
|
import
hashlib
# ######## md5 ########
hash
=
hashlib.md5(bytes(
'898oaFs09f'
,encoding
=
"utf-8"
))
hash
.update(bytes(
'admin'
,encoding
=
"utf-8"
))
print
(
hash
.hexdigest())
|
python內置還有一個 hmac 模塊,它內部對我們創建 key 和 內容 進行進一步的處理然後再加密
1
2
3
4
5
|
import
hmac
h
=
hmac.new(bytes(
'898oaFs09f'
,encoding
=
"utf-8"
))
h.update(bytes(
'admin'
,encoding
=
"utf-8"
))
print
(h.hexdigest())
|
1
2
3
4
5
|
import
random
print
(random.random())
print
(random.randint(
1
,
2
))
print
(random.randrange(
1
,
10
))
|
python中re模塊提供了正則表達式相關操作
字符:
. 匹配除換行符以外的任意字符
\w 匹配字母或數字或下劃線或漢字
\s 匹配任意的空白符
\d 匹配數字
\b 匹配單詞的開始或結束
^ 匹配字符串的開始
$ 匹配字符串的結束
次數:
* 重複零次或更多次
+ 重複一次或更多次
? 重複零次或一次
{n} 重複n次
{n,} 重複n次或更多次
{n,m} 重複n到m次
match
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
# match,從起始位置開始匹配,匹配成功返回一個對象,未匹配成功返回None
match(pattern, string, flags
=
0
)
# pattern: 正則模型
# string : 要匹配的字符串
# falgs : 匹配模式
X VERBOSE Ignore whitespace
and
comments
for
nicer looking RE's.
I IGNORECASE Perform case
-
insensitive matching.
M MULTILINE
"^"
matches the beginning of lines (after a newline)
as well as the string.
"$"
matches the end of lines (before a newline) as well
as the end of the string.
S DOTALL
"."
matches
any
character at
all
, including the newline.
A ASCII For string patterns, make \w, \W, \b, \B, \d, \D
match the corresponding ASCII character categories
(rather than the whole
Unicode
categories, which
is
the
default).
For bytes patterns, this flag
is
the only available
behaviour
and
needn't be specified.
L LOCALE Make \w, \W, \b, \B, dependent on the current locale.
U
UNICODE
For compatibility only. Ignored
for
string patterns (it
is
the default),
and
forbidden
for
bytes patterns.
|
# 無分組 r = re.match("h\w+", origin) print(r.group()) # 獲取匹配到的所有結果 print(r.groups()) # 獲取模型中匹配到的分組結果 print(r.groupdict()) # 獲取模型中匹配到的分組結果 # 有分組 # 爲何要有分組?提取匹配成功的指定內容(先匹配成功全部正則,再匹配成功的局部內容提取出來) r = re.match("h(\w+).*(?P<name>\d)$", origin) print(r.group()) # 獲取匹配到的所有結果 print(r.groups()) # 獲取模型中匹配到的分組結果 print(r.groupdict()) # 獲取模型中匹配到的分組中所有執行了key的組
search
1
2
|
# search,瀏覽整個字符串去匹配第一個,未匹配成功返回None
# search(pattern, string, flags=0)
|
findall
1
2
3
|
# findall,獲取非重複的匹配列表;如果有一個組則以列表形式返回,且每一個匹配均是字符串;如果模型中有多個組,則以列表形式返回,且每一個匹配均是元祖;
# 空的匹配也會包含在結果中
#findall(pattern, string, flags=0)
|
sub
1
2
3
4
5
6
7
8
|
# sub,替換匹配成功的指定位置字符串
sub(pattern, repl, string, count
=
0
, flags
=
0
)
# pattern: 正則模型
# repl : 要替換的字符串或可執行對象
# string : 要匹配的字符串
# count : 指定匹配個數
# flags : 匹配模式
|
split
1
2
3
4
5
6
7
|
# split,根據正則匹配分割字符串
split(pattern, string, maxsplit
=
0
, flags
=
0
)
# pattern: 正則模型
# string : 要匹配的字符串
# maxsplit:指定分割個數
# flags : 匹配模式
|
Python中用於序列化的兩個模塊
Json模塊提供了四個功能:dumps、dump、loads、load
pickle模塊提供了四個功能:dumps、dump、loads、load
configparser用於處理特定格式的文件,其本質上是利用open來操作文件。
1、獲取所有節點
1
2
3
4
5
6
|
import
configparser
config
=
configparser.ConfigParser()
config.read(
'xxxooo'
, encoding
=
'utf-8'
)
ret
=
config.sections()
print
(ret)
|
2、獲取指定節點下所有的鍵值對
1
2
3
4
5
6
|
import
configparser
config
=
configparser.ConfigParser()
config.read(
'xxxooo'
, encoding
=
'utf-8'
)
ret
=
config.items(
'section1'
)
print
(ret)
|
3、獲取指定節點下所有的建
1
2
3
4
5
6
|
import
configparser
config
=
configparser.ConfigParser()
config.read(
'xxxooo'
, encoding
=
'utf-8'
)
ret
=
config.options(
'section1'
)
print
(ret)
|
4、獲取指定節點下指定key的值
1
2
3
4
5
6
7
8
9
10
11
12
|
import
configparser
config
=
configparser.ConfigParser()
config.read(
'xxxooo'
, encoding
=
'utf-8'
)
v
=
config.get(
'section1'
,
'k1'
)
# v = config.getint('section1', 'k1')
# v = config.getfloat('section1', 'k1')
# v = config.getboolean('section1', 'k1')
print
(v)
|
5、檢查、刪除、添加節點
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import
configparser
config
=
configparser.ConfigParser()
config.read(
'xxxooo'
, encoding
=
'utf-8'
)
# 檢查
has_sec
=
config.has_section(
'section1'
)
print
(has_sec)
# 添加節點
config.add_section(
"SEC_1"
)
config.write(
open
(
'xxxooo'
,
'w'
))
# 刪除節點
config.remove_section(
"SEC_1"
)
config.write(
open
(
'xxxooo'
,
'w'
))
|
6、檢查、刪除、設置指定組內的鍵值對
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import
configparser
config
=
configparser.ConfigParser()
config.read(
'xxxooo'
, encoding
=
'utf-8'
)
# 檢查
has_opt
=
config.has_option(
'section1'
,
'k1'
)
print
(has_opt)
# 刪除
config.remove_option(
'section1'
,
'k1'
)
config.write(
open
(
'xxxooo'
,
'w'
))
# 設置
config.
set
(
'section1'
,
'k10'
,
"123"
)
config.write(
open
(
'xxxooo'
,
'w'
))
|
XML是實現不同語言或程序之間進行數據交換的協議,XML文件格式如下:
<data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2023</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2026</year> <gdppc>59900</gdppc> <neighbor direction="N" name="Malaysia" /> </country> <country name="Panama"> <rank updated="yes">69</rank> <year>2026</year> <gdppc>13600</gdppc> <neighbor direction="W" name="Costa Rica" /> <neighbor direction="E" name="Colombia" /> </country> </data>
1、解析XML
from xml.etree import ElementTree as ET # 打開文件,讀取XML內容 str_xml = open('xo.xml', 'r').read() # 將字符串解析成xml特殊對象,root代指xml文件的根節點 root = ET.XML(str_xml)
from xml.etree import ElementTree as ET # 直接解析xml文件 tree = ET.parse("xo.xml") # 獲取xml文件的根節點 root = tree.getroot()
2、操作XML
XML格式類型是節點嵌套節點,對於每一個節點均有以下功能,以便對當前節點進行操作:
由於 每個節點 都具有以上的方法,並且在上一步驟中解析時均得到了root(xml文件的根節點),so 可以利用以上方法進行操作xml文件。
a. 遍歷XML文檔的所有內容
View Codeb、遍歷XML中指定的節點
View Codec、修改節點內容
由於修改的節點時,均是在內存中進行,其不會影響文件中的內容。所以,如果想要修改,則需要重新將內存中的內容寫到文件。
解析字符串方式,修改,保存解析文件方式,修改,保存d、刪除節點
解析字符串方式打開,刪除,保存解析文件方式打開,刪除,保存
3、創建XML文檔
from xml.etree import ElementTree as ET # 創建根節點 root = ET.Element("famliy") # 創建節點大兒子 son1 = ET.Element('son', {'name': '兒1'}) # 創建小兒子 son2 = ET.Element('son', {"name": '兒2'}) # 在大兒子中創建兩個孫子 grandson1 = ET.Element('grandson', {'name': '兒11'}) grandson2 = ET.Element('grandson', {'name': '兒12'}) son1.append(grandson1) son1.append(grandson2) # 把兒子添加到根節點中 root.append(son1) root.append(son1) tree = ET.ElementTree(root) tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)
from xml.etree import ElementTree as ET # 創建根節點 root = ET.Element("famliy") # 創建大兒子 # son1 = ET.Element('son', {'name': '兒1'}) son1 = root.makeelement('son', {'name': '兒1'}) # 創建小兒子 # son2 = ET.Element('son', {"name": '兒2'}) son2 = root.makeelement('son', {"name": '兒2'}) # 在大兒子中創建兩個孫子 # grandson1 = ET.Element('grandson', {'name': '兒11'}) grandson1 = son1.makeelement('grandson', {'name': '兒11'}) # grandson2 = ET.Element('grandson', {'name': '兒12'}) grandson2 = son1.makeelement('grandson', {'name': '兒12'}) son1.append(grandson1) son1.append(grandson2) # 把兒子添加到根節點中 root.append(son1) root.append(son1) tree = ET.ElementTree(root) tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)
from xml.etree import ElementTree as ET # 創建根節點 root = ET.Element("famliy") # 創建節點大兒子 son1 = ET.SubElement(root, "son", attrib={'name': '兒1'}) # 創建小兒子 son2 = ET.SubElement(root, "son", attrib={"name": "兒2"}) # 在大兒子中創建一個孫子 grandson1 = ET.SubElement(son1, "age", attrib={'name': '兒11'}) grandson1.text = '孫子' et = ET.ElementTree(root) #生成文檔對象 et.write("test.xml", encoding="utf-8", xml_declaration=True, short_empty_elements=False)
由於原生保存的XML時默認無縮進,如果想要設置縮進的話, 需要修改保存方式:
4、命名空間
詳細介紹,猛擊這裏
Python標準庫中提供了:urllib等模塊以供Http請求,但是,它的 API 太渣了。它是爲另一個時代、另一個互聯網所創建的。它需要巨量的工作,甚至包括各種方法覆蓋,來完成最簡單的任務。
import urllib.request f = urllib.request.urlopen('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508') result = f.read().decode('utf-8')
import urllib.request req = urllib.request.Request('http://www.example.com/') req.add_header('Referer', 'http://www.python.org/') r = urllib.request.urlopen(req) result = f.read().decode('utf-8')
注:更多見Python官方文檔:https://docs.python.org/3.5/library/urllib.request.html#module-urllib.request
Requests 是使用 Apache2 Licensed 許可證的 基於Python開發的HTTP 庫,其在Python內置模塊的基礎上進行了高度的封裝,從而使得Pythoner進行網絡請求時,變得美好了許多,使用Requests可以輕而易舉的完成瀏覽器可有的任何操作。
1、安裝模塊
1
|
pip3 install requests
|
2、使用模塊
# 1、無參數實例 import requests ret = requests.get('https://github.com/timeline.json') print(ret.url) print(ret.text) # 2、有參數實例 import requests payload = {'key1': 'value1', 'key2': 'value2'} ret = requests.get("http://httpbin.org/get", params=payload) print(ret.url) print(ret.text)
更多requests模塊相關的文檔見:http://cn.python-requests.org/zh_CN/latest/
3、Http請求和XML實例
實例:檢測QQ賬號是否在線
實例:查看火車停靠信息
注:更多接口猛擊這裏
用於便捷記錄日誌且線程安全的模塊
1、單文件日誌
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import
logging
logging.basicConfig(filename
=
'log.log'
,
format
=
'%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s'
,
datefmt
=
'%Y-%m-%d %H:%M:%S %p'
,
level
=
10
)
logging.debug(
'debug'
)
logging.info(
'info'
)
logging.warning(
'warning'
)
logging.error(
'error'
)
logging.critical(
'critical'
)
logging.log(
10
,
'log'
)
|
日誌等級:
CRITICAL = 50 FATAL = CRITICAL ERROR = 40 WARNING = 30 WARN = WARNING INFO = 20 DEBUG = 10 NOTSET = 0
注:只有【當前寫等級】大於【日誌等級】時,日誌文件才被記錄。
日誌記錄格式:
2、多文件日誌
對於上述記錄日誌的功能,只能將日誌記錄在單文件中,如果想要設置多個日誌文件,logging.basicConfig將無法完成,需要自定義文件和日誌操作對象。
如上述創建的兩個日誌對象
可以執行shell命令的相關模塊和函數有:
以上執行shell命令的相關的模塊和函數的功能均在 subprocess 模塊中實現,並提供了更豐富的功能。
call
執行命令,返回狀態碼
1
2
|
ret
=
subprocess.call([
"ls"
,
"-l"
], shell
=
False
)
ret
=
subprocess.call(
"ls -l"
, shell
=
True
)
|
check_call
執行命令,如果執行狀態碼是 0 ,則返回0,否則拋異常
1
2
|
subprocess.check_call([
"ls"
,
"-l"
])
subprocess.check_call(
"exit 1"
, shell
=
True
)
|
check_output
執行命令,如果狀態碼是 0 ,則返回執行結果,否則拋異常
1
2
|
subprocess.check_output([
"echo"
,
"Hello World!"
])
subprocess.check_output(
"exit 1"
, shell
=
True
)
|
subprocess.Popen(...)
用於執行復雜的系統命令
參數:
終端輸入的命令分爲兩種:
高級的 文件、文件夾、壓縮包 處理模塊
shutil.copyfileobj(fsrc, fdst[, length])
將文件內容拷貝到另一個文件中
1
2
3
|
import
shutil
shutil.copyfileobj(
open
(
'old.xml'
,
'r'
),
open
(
'new.xml'
,
'w'
))
|
shutil.copyfile(src, dst)
拷貝文件
1
|
shutil.copyfile(
'f1.log'
,
'f2.log'
)
|
shutil.copymode(src, dst)
僅拷貝權限。內容、組、用戶均不變
1
|
shutil.copymode(
'f1.log'
,
'f2.log'
)
|
shutil.copystat(src, dst)
僅拷貝狀態的信息,包括:mode bits, atime, mtime, flags
1
|
shutil.copystat(
'f1.log'
,
'f2.log'
)
|
shutil.copy(src, dst)
拷貝文件和權限
1
2
3
|
import
shutil
shutil.copy(
'f1.log'
,
'f2.log'
)
|
shutil.copy2(src, dst)
拷貝文件和狀態信息
1
2
3
|
import
shutil
shutil.copy2(
'f1.log'
,
'f2.log'
)
|
shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
遞歸的去拷貝文件夾
1
2
3
|
import
shutil
shutil.copytree(
'folder1'
,
'folder2'
, ignore
=
shutil.ignore_patterns(
'*.pyc'
,
'tmp*'
))
|
shutil.rmtree(path[, ignore_errors[, onerror]])
遞歸的去刪除文件
1
2
3
|
import
shutil
shutil.rmtree(
'folder1'
)
|
shutil.move(src, dst)
遞歸的去移動文件,它類似mv命令,其實就是重命名。
1
2
3
|
import
shutil
shutil.move(
'folder1'
,
'folder3'
)
|
shutil.make_archive(base_name, format,...)
創建壓縮包並返回文件路徑,例如:zip、tar
創建壓縮包並返回文件路徑,例如:zip、tar
1
2
3
4
5
6
7
8
|
#將 /Users/wupeiqi/Downloads/test 下的文件打包放置當前程序目錄
import
shutil
ret
=
shutil.make_archive(
"wwwwwwwwww"
,
'gztar'
, root_dir
=
'/Users/wupeiqi/Downloads/test'
)
#將 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目錄
import
shutil
ret
=
shutil.make_archive(
"/Users/wupeiqi/wwwwwwwwww"
,
'gztar'
, root_dir
=
'/Users/wupeiqi/Downloads/test'
)
|
shutil 對壓縮包的處理是調用 ZipFile 和 TarFile 兩個模塊來進行的,詳細:
paramiko是一個用於做遠程控制的模塊,使用該模塊可以對遠程服務器進行命令或文件操作,值得一說的是,fabric和ansible內部的遠程管理就是使用的paramiko來現實。
1、下載安裝