python文件转码_Python转码&解压&多进程

本文介绍了一种使用Python进行文件解压(包括.zip和.tar.gz)的方法,并利用多进程加快处理速度。代码中定义了unzipDayFile()和untarDayFile()函数分别处理zip和tar.gz文件,然后通过Pool()创建多进程来并行解压,大大减少了处理时间。
摘要由CSDN通过智能技术生成

import zipfile

import tarfile

import gzip

import os

from time import ctime

from multiprocessing import Pool

from multiprocessing import cpu_count

dayZipsPath = r'.'

quarterZipsPath = r'./tmp'

zipPassWord = b'password'

mrFilePath = r'./data'

def unzipDayFile():

for file_name in os.listdir(dayZipsPath):

if os.path.splitext(file_name)[1] == '.zip':

print( file_name)

file_zip = zipfile.ZipFile(file_name, 'r')

file_zip.extractall(path = quarterZipsPath, pwd = zipPassWord)

file_zip.close()

#os.remove(file_name)

def untarDayFile():

for file_name in os.listdir(dayZipsPath):

if '.tar.gz' in file_name:

print( file_name)

file_tar = tarfile.open(file_name)

file_tar.extractall(path = quarterZipsPath)

file_tar.close()

#os.remove(file_name)

def unzip(zipsList):

for file_name in zipsList:

if os.path.splitext(file_name)[1] == '.zip':

zipFileName = quarterZipsPath +'/'+ file_name

file_zip = zipfile.ZipFile(zipFileName, 'r')

file_zip.extractall(path = mrFilePath, pwd = zipPassWord)

file_zip.close()

os.remove(zipFileName)

if __name__ == '__main__':

print('Begin:%s' % ctime())

#获取CPU核个数

cpuNum = cpu_count()

print(cpuNum)

unzipDayFile()

untarDayFile()

#多进程解压,大大缩短处理时间

quarterZipsList = list(os.listdir(quarterZipsPath))

zipFileNum = len(quarterZipsList)

print("total zip files num:%d" % (zipFileNum))

print("begin unzip:%s" % ctime())

p = Pool()

for i in range(cpuNum):

beginPos = int(i*zipFileNum/cpuNum)

endPos = min(int((i+1)*zipFileNum/cpuNum),zipFileNum)

print("proc %d - %d" % (beginPos, endPos))

p.apply_async(unzip,args=(quarterZipsList[beginPos:endPos],))

print("waiting for unzip quarter mr data ...")

p.close()

p.join()

print("end unzip:%s" % ctime())

print( "End:%s" % ctime())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值