溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python怎么使用shutil操作文件和subprocess運(yùn)行子程序

發(fā)布時(shí)間:2023-05-11 10:42:27 來(lái)源:億速云 閱讀:83 作者:zzz 欄目:編程語(yǔ)言

本文小編為大家詳細(xì)介紹“Python怎么使用shutil操作文件和subprocess運(yùn)行子程序”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“Python怎么使用shutil操作文件和subprocess運(yùn)行子程序”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來(lái)學(xué)習(xí)新知識(shí)吧。

一、shutil模塊(了解):高級(jí)的文件、文件夾、壓縮包處理模塊。

import shutil

# shutil.copyfileobj(fsrc, fdst[, length]),將文件內(nèi)容拷貝到另一個(gè)文件中
shutil.copyfileobj(open('old.xml', 'r'), open('new.xml', 'w'))

# shutil.copyfile(src, dst),拷貝文件
shutil.copyfile('f1.log', 'f2.log')  # 目標(biāo)文件無(wú)需存在

# shutil.copymode(src, dst),僅拷貝權(quán)限。內(nèi)容、組、用戶均不變
shutil.copymode('f1.log', 'f2.log')  # 目標(biāo)文件必須存在

# shutil.copystat(src, dst),僅拷貝狀態(tài)的信息,包括:mode bits, atime, mtime, flags
shutil.copystat('f1.log', 'f2.log')  # 目標(biāo)文件必須存在

# shutil.copy(src, dst),拷貝文件和權(quán)限
shutil.copy('f1.log', 'f2.log')

# shutil.copy2(src, dst),拷貝文件和狀態(tài)信息
shutil.copy2('f1.log', 'f2.log')

# shutil.ignore_patterns(*patterns)
# shutil.copytree(src, dst, symlinks=False, ignore=None),遞歸的去拷貝文件夾
# 目標(biāo)目錄不能存在,注意對(duì)folder2目錄父級(jí)目錄要有可寫(xiě)權(quán)限,ignore的意思是排除
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))

# shutil.rmtree(path[, ignore_errors[, onerror]]),遞歸的去刪除文件
shutil.rmtree('folder1')

# shutil.move(src, dst),遞歸的去移動(dòng)文件,它類似mv命令,其實(shí)就是重命名
shutil.move('folder1', 'folder3')

# shutil.make_archive(base_name, format, ...),創(chuàng)建壓縮包并返回文件路徑,例如:zip、tar
'''
base_name: 壓縮包的文件名,也可以是壓縮包的路徑。只是文件名時(shí),則保存至當(dāng)前目錄,否則保存至指定路徑,如 data_bak = >保存至當(dāng)前路徑;/ tmp/data_bak = >保存至/tmp/
format:壓縮包種類,“zip”, “tar”, “bztar”,“gztar”
root_dir:要壓縮的文件夾路徑(默認(rèn)當(dāng)前目錄)
owner:用戶,默認(rèn)當(dāng)前用戶
group:組,默認(rèn)當(dāng)前組
logger:用于記錄日志,通常是logging.Logger對(duì)象
'''

# 將 /data 下的文件打包放置當(dāng)前程序目錄
ret = shutil.make_archive("data_bak", 'gztar', root_dir='/data')

# 將 /data下的文件打包放置 /tmp/目錄
ret = shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data')

shutil 對(duì)壓縮包的處理是調(diào)用 ZipFile 和 TarFile 兩個(gè)模塊來(lái)進(jìn)行的,詳細(xì):

1、 zipfile壓縮解壓縮
import zipfile

# 壓縮
z = zipfile.ZipFile('laxi.zip', 'w')
z.write('a.log')
z.write('data.data')
z.close()

# 解壓
z = zipfile.ZipFile('laxi.zip', 'r')
z.extractall(path='.')
z.close()
2、 tarfile壓縮解壓縮
import tarfile

# 壓縮
t=tarfile.open('/tmp/egon.tar','w')
t.add('/test1/a.py',arcname='a.bak')
t.add('/test1/b.py',arcname='b.bak')
t.close()


# 解壓
t=tarfile.open('/tmp/egon.tar','r')
t.extractall('/egon')
t.close()

二、subprocess模塊(了解):運(yùn)行子程序

subprocess模塊允許你去創(chuàng)建一個(gè)新的進(jìn)程讓其執(zhí)行另外的程序,并與它進(jìn)行通信,獲取標(biāo)準(zhǔn)的輸入、標(biāo)準(zhǔn)輸出、標(biāo)準(zhǔn)錯(cuò)誤以及返回碼等。

import subprocess
'''
sh-3.2# ls /Users/nick/Desktop |grep txt$
mysql.txt
tt.txt
事物.txt
'''

res1 = subprocess.Popen('ls /Users/jieli/Desktop',shell=True, stdout=subprocess.PIPE)
res = subprocess.Popen('grep txt$', shell=True,stdin=res1.stdout, stdout=subprocess.PIPE)
print(res.stdout.read().decode('utf-8'))

# 下面這段等同于上面,但是上面的優(yōu)勢(shì)在于,一個(gè)數(shù)據(jù)流可以和另外一個(gè)數(shù)據(jù)流交互,可以通過(guò)爬蟲(chóng)得到結(jié)果然后交給grep。
res1 = subprocess.Popen('ls /Users/jieli/Desktop |grep txt$',shell=True, stdout=subprocess.PIPE)
print(res1.stdout.read().decode('utf-8'))

# windows下:
# dir | findstr 'test*'
# dir | findstr 'txt$'
res1 = subprocess.Popen(r'dir “C:\Users\Administrator\PycharmProjects\test\函數(shù)備課”',  shell=True, stdout=subprocess.PIPE)
res = subprocess.Popen('findstr test*', shell=True,  stdin=res1.stdout,   stdout=subprocess.PIPE)

# subprocess使用當(dāng)前系統(tǒng)默認(rèn)編碼,得到結(jié)果為bytes類型,在windows下需要用gbk解碼
print(res.stdout.read().decode('gbk') )

讀到這里,這篇“Python怎么使用shutil操作文件和subprocess運(yùn)行子程序”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過(guò)才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI