1. 程式人生 > >python 學習之路day19---其餘常用模組

python 學習之路day19---其餘常用模組

1.os模組

os表示作業系統

該模組主要處理與作業系統相關的操作,最常用的是檔案操作:1.開啟 2.讀取 3.寫入 4.刪除 5.複製 6.重新命名

os.getcwd() 獲取當前工作目錄,即當前python指令碼工作的目錄路徑
os.chdir("dirname")  改變當前指令碼工作目錄;相當於shell下cd
os.curdir  返回當前目錄: ('.')
os.pardir  獲取當前目錄的父目錄字串名:('..')
os.makedirs('dirname1/dirname2')    可生成多層遞迴目錄
os.removedirs('dirname1
') 若目錄為空,則刪除,並遞迴到上一級目錄,如若也為空,則刪除,依此類推 os.mkdir('dirname') 生成單級目錄;相當於shell中mkdir dirname os.rmdir('dirname') 刪除單級空目錄,若目錄不為空則無法刪除,報錯;相當於shell中rmdir dirname os.listdir('dirname') 列出指定目錄下的所有檔案和子目錄,包括隱藏檔案,並以列表方式列印 os.remove() 刪除一個檔案 os.rename("oldname","newname") 重新命名檔案/目錄 os.stat('path/filename
') 獲取檔案/目錄資訊 os.sep 輸出作業系統特定的路徑分隔符,win下為"\\",Linux下為"/" os.linesep 輸出當前平臺使用的行終止符,win下為"\t\n",Linux下為"\n" os.pathsep 輸出用於分割檔案路徑的字串 win下為;,Linux下為: 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所指向的檔案或者目錄的最後修改時間 os.path.getsize(path) 返回path的大小
os模組的方法
在Linux和Mac平臺上,該函式會原樣返回path,在windows平臺上會將路徑中所有字元轉換為小寫,並將所有斜槓轉換為飯斜槓。
>>> os.path.normcase('c:/windows\\system32\\')   
'c:\\windows\\system32\\'   
   

規範化路徑,如..和/
>>> os.path.normpath('c://windows\\System32\\../Temp/')   
'c:\\windows\\Temp'   

>>> a='/Users/jieli/test1/\\\a1/\\\\aa.py/../..'
>>> print(os.path.normpath(a))
/Users/jieli/test1
os.path.normcase方法

什麼時候會用到os模組?

當需要操作檔案及資料夾的時候,重點放在對檔案的增刪改查。

2.subprocess模組

subprocess翻譯為子程序,程序指的是正在執行的程式,子程序是由另一個正在執行程式啟動的程式,例如:qq聊天,點選了一個連結,打開了瀏覽器,那麼瀏覽器稱之為qq的子程序。

為什麼要使用子程序?

當我們有一個任務需要處理,而自己的程式無法處理,所以需要開啟另外一個程式。

#1.例如想要在python中獲取當前系統所有的程序資訊,可以呼叫os模組的system的方法
import os
os.system("tasklist")

 

System Idle Process 0 Services 0 4 K
System 4 Services 0 5,412 K
smss.exe 400 Services 0 1,176 K
csrss.exe 616 Services 0 4,676 K
wininit.exe 756 Services 0 5,804 K
services.exe 868 Services 0 7,432 K
lsass.exe 888 Services 0 15,028 K
svchost.exe 984 Services 0 20,480 K
svchost.exe 344 Services 0 10,120 K
svchost.exe 1004 Services 0 20,488 K
svchost.exe 1048 Services 0 40,540 K
svchost.exe 1076 Services 0 25,424 K
WUDFHost.exe 1180 Services 0 34,488 K
QQPCRTP.exe 1364 Services 0 26,784 K
svchost.exe 1420 Services 0 31,472 K
svchost.exe 1716 Services 0 26,972 K
svchost.exe 1892 Services 0 9,792 K
svchost.exe 1980 Services 0 19,540 K
svchost.exe 2000 Services 0 11,588 K
svchost.exe 1440 Services 0 15,968 K
spoolsv.exe 1848 Services 0 14,676 K
AlibabaProtect.exe 2284 Services 0 14,316 K
dasHost.exe 2332 Services 0 18,220 K
svchost.exe 2456 Services 0 304 K
GATESRV.exe 2536 Services 0 840 K
wlanext.exe 2544 Services 0 7,024 K
PnkBstrB.exe 2568 Services 0 6,528 K
QQProtect.exe 2628 Services 0 3,608 K
PnkBstrA.exe 2636 Services 0 6,356 K
conhost.exe 2656 Services 0 5,124 K
vmnetdhcp.exe 2668 Services 0 10,992 K
pcas.exe 2724 Services 0 1,056 K
svchost.exe 2760 Services 0 16,492 K
OfficeUpdate.exe 2800 Services 0 3,276 K
SearchIndexer.exe 2808 Services 0 49,448 K
svchost.exe 2816 Services 0 17,448 K
vmnat.exe 2856 Services 0 7,076 K
vmware-usbarbitrator64.ex 2888 Services 0 256 K
wwbizsrv.exe 2896 Services 0 2,540 K
svchost.exe 3272 Services 0 7,932 K
svchost.exe 484 Services 0 10,592 K
csrss.exe 9272 Console 2 43,060 K
winlogon.exe 4668 Console 2 10,232 K
dwm.exe 584 Console 2 103,960 K
MasterHelper.exe 10028 Console 2 2,424 K
ProcHelper64.exe 8616 Console 2 304 K
svchost.exe 6956 Console 2 20,468 K
sihost.exe 7732 Console 2 22,316 K
taskhostw.exe 8832 Console 2 22,136 K
ChsIME.exe 4024 Console 2 7,956 K
RuntimeBroker.exe 10068 Console 2 20,668 K
explorer.exe 2928 Console 2 225,192 K
QQPCTray.exe 6124 Console 2 60,660 K
ShellExperienceHost.exe 6192 Console 2 84,340 K
SearchUI.exe 9528 Console 2 119,788 K
DriveTheLife.exe 6504 Console 2 5,288 K
QQPCNetFlow.exe 7236 Console 2 7,304 K
QQPCRealTimeSpeedup.exe 8228 Console 2 51,328 K
UpdateSoftTip.exe 9036 Console 2 5,080 K
SoftMgrUpdateNotify.exe 9856 Console 2 660 K
SogouCloud.exe 4672 Console 2 7,040 K
DispcapHelper.exe 9552 Console 2 488 K
pycharm.exe 3928 Console 2 436,012 K
fsnotifier.exe 5208 Console 2 356 K
conhost.exe 2240 Console 2 9,328 K
QMDeskTopGC.exe 5868 Console 2 2,572 K
QQ.exe 4700 Console 2 142,108 K
TXPlatform.exe 3996 Console 2 96 K
PDZipTool.exe 5816 Console 2 10,132 K
ApplicationFrameHost.exe 1900 Console 2 33,608 K
wpscloudsvr.exe 7524 Console 2 26,568 K
wpscenter.exe 7956 Console 2 12,352 K
WmiPrvSE.exe 7908 Services 0 13,348 K
SogouImeBroker.exe 4660 Console 2 216 K
chrome.exe 8600 Console 2 147,556 K
chrome.exe 724 Console 2 1,096 K
chrome.exe 1784 Console 2 760 K
chrome.exe 7628 Console 2 4,980 K
chrome.exe 7160 Console 2 6,600 K
chrome.exe 4512 Console 2 7,688 K
chrome.exe 8044 Console 2 57,600 K
SystemSettingsBroker.exe 7408 Console 2 20,704 K
StudentMain.exe 9432 Console 2 7,460 K
chrome.exe 5100 Console 2 52,748 K
chrome.exe 11220 Console 2 51,004 K
chrome.exe 10812 Console 2 6,576 K
chrome.exe 9536 Console 2 7,120 K
chrome.exe 7332 Console 2 69,372 K
cloudmusic.exe 6420 Console 2 40,900 K
cloudmusic.exe 6808 Console 2 34,800 K
cloudmusic.exe 11116 Console 2 33,428 K
audiodg.exe 4300 Services 0 24,808 K
chrome.exe 11196 Console 2 4,884 K
WUDFHost.exe 9596 Services 0 8,300 K
QMUsbGuard.exe 10436 Console 2 10,812 K
wpscenter.exe 7712 Console 2 2,460 K
SearchProtocolHost.exe 4688 Services 0 11,360 K
SearchFilterHost.exe 7188 Services 0 8,584 K
SGTool.exe 10976 Console 2 18,100 K
python.exe 7872 Console 2 30,584 K
conhost.exe 10264 Console 2 9,604 K
cmd.exe 11468 Console 2 2,792 K
tasklist.exe 11940 Console 2 7,932 K
結果如下:

os.system和subprocess的區別

os.system可以執行系統指令,命令作業系統開啟一個應用程式,然而os.system在執行命令的時候直接把結果返回到了控制檯,如果我們需要獲取執行的結果,os,system無能為力。

subprocess不僅可以啟動子程序,還能與子程序。

 

import subprocess
p1 = subprocess.Popen("dir",shell=True,stdout=subprocess.PIPE)


#dir表示的是一個需要執行的命令語句,必須加上雙引號。
#shell表示dir是一個命令
#stdout 指定輸出管道,相當於生活中的水管 水可以通過管道 從一個地方流到另一個地方
# 在程式中  資料相當於水   管道的作用,就從一個程序中把資料傳輸到另一個程序。
subprocess.Popen的常用引數!!!

上面程式碼是 啟動了一個dir子程序 並將結果輸出到指定管道。

小練習:

1.啟動一個tasklist子程序 指定輸出結果到管道中

2.啟動一個findstr的子程序 將p1程序的結果作為p2程序輸入

# 1.啟動一個tasklist子程序 指定輸出結果到管道中
#
# 2.啟動一個findstr的子程序 將p1程序的結果作為p2程序輸入,findstr單獨顯示cmd.exe的詳細資訊
import subprocess
p1=subprocess.Popen('tasklist',shell=True,stdout=subprocess.PIPE)


p2=subprocess.Popen('findstr cmd',shell=True,stdin=p1.stdout,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

print(p2.stdout.read())


print(p2.stderr.read().decode('GBK'))   #當p2這個子程序出錯時,錯誤資訊會在錯誤管道stderr中被獲取
小練習題解

3.configparser

configparser模組的基本操作

 
 
"""
configerparser模組是用來寫配置檔案的,首先需要了解配置檔案xxx.clg的內容是怎麼樣的。 如下:在一個cfg檔案中的內容格式如下: -------------------------------------------- [mysql] #代表分割槽 username = jack 分割槽中的名稱(變數) password = 123 lock = true [django] . . . -------------------------------------------- 一個cfg中可以有多個分割槽,一個分割槽也可以有多個名稱(變數)
""" #configparser基本操作 import configparser cfg=configparser.ConfigParser() # 建立一個配置檔案解析器 cfg.read('my_config.cfg',encoding='utf-8') # 讀取名為my_config.cfg的配置檔案 print(cfg.sections()) #獲取cfg中的分割槽,返回值是一個列表

>>>:['mysql', 'json'] # 獲取某個分割槽下的某個選項 第一個引數分割槽名 第二個選項名稱 username = cfg.get("mysql","username") print(username) print(type(username))
>>>:
egon
<class 'str'>
# 以下三個函式是幫你封裝了 型別轉換
#  cfg.getfloat()
password = cfg.getfloat("mysql","password")
print(password)
print(type(password))

>>>:

123456.0
<class 'float'>

# cfg.getint()
password = cfg.getint("mysql","password")
print(password)
print(type(password))

>>>:

123456
<class 'int'>

# cfg.getboolean()
lock=cfg.getboolean('mysql','lock')
print(lock)
print(type(lock))
>>>:

False
<class 'bool'>

configparser模組的增刪改查

import configparser
cfg = configparser.ConfigParser()
cfg.read("my_config.cfg",encoding="utf-8")

#修改
# 將mysql分割槽下的lock改為True
cfg.set('mysql','lock','True')
#由於此時還是在記憶體中修改,所以需要把修改後的cfg檔案覆蓋原來的cfg檔案
with open('my_config.cfg','wt',encoding='utf-8')as f:
    cfg.write(f)
#-------------------------------------------------------------------
#在mysql分割槽中新增新的分割槽,也需要寫入檔案覆蓋
cfg.add_section('新分割槽')   #如果重複寫入,會報錯,只要配置檔案中已經存在那就不能再寫入
#在mysql分割槽中新增新的選項  port 值為3306,也需要寫入檔案覆蓋
cfg.set('mysql','port','3306')
with open('my_config.cfg','wt',encoding='utf-8')as f:
    cfg.write(f)

#-------------------------------------------------------------------
#刪除一個分割槽
cfg.remove_section('新分割槽')
# 刪除某個分割槽的選項
cfg.remove_option('mysql','port')
with open('my_config.cfg','wt',encoding='utf-8')as f:
    cfg.write(f)
#-------------------------------------------------------------------
# 判斷是否存在某個分割槽
print(cfg.has_section('新分割槽'))
# 判斷是否存在某個選項
print(cfg.has_option('mysql','username'))

4.shutil模組

shutil模組介紹

shutil模組時一個工具包,封裝了檔案高階操作,讓你操作起來更方便,其功能與os有些重疊,但是os只能處理檔案存在,路徑存在等問題,無法直接完成copy等操作,而shutil則有這類操作,並且還提供了壓縮與解壓操作。

shutil拷貝操作

import shutil
#shutil.copyfileobj(fsrc, fdst[, length])   將檔案內容拷貝到另一個檔案中
shutil.copyfileobj(open('a.json','r'), open('new.json', 'w'))  #被拷貝檔案必須存在

#shutil.copyfile(src, dst)   拷貝檔案
shutil.copyfile('a.json', 'a1.json')  #目標檔案無需存在

# shutil.copystat(src, dst)   #僅拷貝狀態的資訊,包括:mode#,bits, atime, mtime, flags

shutil.copystat('f1.log', 'f2.log')  # 目標檔案必須存在

# shutil.copy(src, dst)  # 拷貝檔案和許可權

shutil.copy('f1.log', 'f2.log')

# hutil.copy2(src, dst)   拷貝檔案和狀態資訊

shutil.copy2('f1.log', 'f2.log')

# shutil.ignore_patterns(*patterns)
# shutil.copytree(src, dst, symlinks=False, ignore=None)      遞迴的去拷貝資料夾

shutil.copytree('folder1', 'folder2',
                ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))  # 目標目錄不能存在,注意對folder2目錄父級目錄要有可寫許可權,ignore的意思是排除

#shutil.rmtree(path[, ignore_errors[, onerror]])   遞迴的去刪除檔案


shutil.rmtree('folder1')

# shutil.move(src, dst)   遞迴的去移動檔案,它類似mv命令,其實就是重新命名。

shutil.move('folder1', 'folder3')

shutil壓縮解壓操作

import shutil

# 壓縮   將 D:\學習\old_boy_study\homework\草稿 下的檔案打包放置當前程式目錄,命名為1.py.zip
shutil.make_archive("1.py",
                    "zip",
                    r"D:\學習\old_boy_study\homework\草稿"
                    )


#解壓
shutil.unpack_archive("1.py.zip",
                      r"D:\學習\old_boy_study\homework\草稿\這是解壓的檔案",
                      'zip')