阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

教你Python使用shutil操作文件、subprocess运行子程序的方法

33次阅读
没有评论

共计 3841 个字符,预计需要花费 10 分钟才能阅读完成。

导读 这篇文章介绍了 Python 使用 shutil 操作文件、subprocess 运行子程序的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
一、shutil 模块(了解):高级的文件、文件夹、压缩包处理模块。
import shutil
 
# shutil.copyfileobj(fsrc, fdst[, length]),将文件内容拷贝到另一个文件中
shutil.copyfileobj(open('old.xml', 'r'), open('new.xml', 'w'))
 
# shutil.copyfile(src, dst),拷贝文件
shutil.copyfile('f1.log', 'f2.log')  # 目标文件无需存在
 
# shutil.copymode(src, dst),仅拷贝权限。内容、组、用户均不变
shutil.copymode('f1.log', 'f2.log')  # 目标文件必须存在
 
# 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')
 
# shutil.copy2(src, dst),拷贝文件和状态信息
shutil.copy2('f1.log', 'f2.log')
 
# shutil.ignore_patterns(*patterns)
# shutil.copytree(src, dst, symlinks=False, ignore=None),递归的去拷贝文件夹
# 目标目录不能存在,注意对 folder2 目录父级目录要有可写权限,ignore 的意思是排除
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
 
# shutil.rmtree(path[, ignore_errors[, onerror]]),递归的去删除文件
shutil.rmtree('folder1')
 
# shutil.move(src, dst),递归的去移动文件,它类似 mv 命令,其实就是重命名
shutil.move('folder1', 'folder3')
 
# shutil.make_archive(base_name, format, ...),创建压缩包并返回文件路径,例如:zip、tar
'''
base_name:压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,如 data_bak = > 保存至当前路径;/ tmp/data_bak = > 保存至 /tmp/
format:压缩包种类,“zip”,“tar”,“bztar”,“gztar”root_dir:要压缩的文件夹路径(默认当前目录)owner:用户,默认当前用户
group:组,默认当前组
logger:用于记录日志,通常是 logging.Logger 对象
'''
 
# 将 /data 下的文件打包放置当前程序目录
ret = shutil.make_archive("data_bak", 'gztar', root_dir='/data')
 
# 将 /data 下的文件打包放置 /tmp/ 目录
ret = shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data')

shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:

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 模块 (了解):运行子程序

subprocess 模块允许你去创建一个新的进程让其执行另外的程序,并与它进行通信,获取标准的输入、标准输出、标准错误以及返回码等。

更多查看官网:https://docs.python.org/2/library/subprocess.html?highlight=subprocess#frequently-used-arguments

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'))
 
# 下面这段等同于上面, 但是上面的优势在于, 一个数据流可以和另外一个数据流交互, 可以通过爬虫得到结果然后交给 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\ 函数备课”',  shell=True, stdout=subprocess.PIPE)
res = subprocess.Popen('findstr test*', shell=True,  stdin=res1.stdout,   stdout=subprocess.PIPE)
 
# subprocess 使用当前系统默认编码,得到结果为 bytes 类型,在 windows 下需要用 gbk 解码
print(res.stdout.read().decode('gbk') )
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'))

# 下面这段等同于上面, 但是上面的优势在于, 一个数据流可以和另外一个数据流交互, 可以通过爬虫得到结果然后交给 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\ 函数备课”',  shell=True, stdout=subprocess.PIPE)
res = subprocess.Popen('findstr test*', shell=True,  stdin=res1.stdout,   stdout=subprocess.PIPE)

# subprocess 使用当前系统默认编码,得到结果为 bytes 类型,在 windows 下需要用 gbk 解码
print(res.stdout.read().decode('gbk') )

到此这篇关于 Python 使用 shutil 操作文件、subprocess 运行子程序的文章就介绍到这了。

阿里云 2 核 2G 服务器 3M 带宽 61 元 1 年,有高配

腾讯云新客低至 82 元 / 年,老客户 99 元 / 年

代金券:在阿里云专用满减优惠券

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2024-07-25发表,共计3841字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中