递归获取目录下的所有压缩文件并解压(Python3)

该代码示例展示了如何使用Python递归遍历指定目录,查找.zip和.rar文件并使用winrar进行解压。另外,还提供了C++代码片段,用于获取所有子文件,但未实现解压功能,适用于Windows平台。对于大量文件的解压,C++可能提供更快的速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

递归找到nowPath下的所有.zip和.rar文件并用winrar解压

import os 
import sys
import re
from pathlib import Path as ph
class UnZip():
	nowPath="O:/"
	
	zipRe=re.compile(".zip$")
	rarRe=re.compile(".rar$")
	rarComm="winrar x "

	def __init__(self):
		self.get(self.nowPath)
	
	def get(self,nowPath):
		nowDir=os.listdir(nowPath)
		for i in nowDir:
			if(ph(nowPath+'/'+i).is_dir()):
				self.get(nowPath+"/"+i)
			else:
				if(self.zipRe.search(i) or self.rarRe.search(i)):
					os.chdir(nowPath)
					nowComm=self.rarComm+i
					os.system(nowComm)
					

if __name__=="__main__":
	a=UnZip()

如果文件太多,这样的操作其实还是比较慢,为此使用C++进行解压速度更快。
下面代码是使用WinAPI获取所有子文件。并未进行字符串匹配从而筛选出对应的压缩文件。其代码也只适用于Windows平台。
其中使用的API可以在windows的API搜索中寻找对应的解释。

getAllFile.h

#include<stdio.h>
#include<stdlib.h>
#include<windows.h>

#pragma once
void getAllFile(char* nowpath);

getAllFile.cpp

#include<getAllFile.h>

void getAllFile(char* nowPath) {
	WIN32_FIND_DATAA stFD;
	HANDLE h;
	HANDLE nowHand;
	char nowFloderPath[FILENAMELEN];
	char nowDirPath[FILENAMELEN];
	strcpy(nowDirPath, nowPath);
	strcpy(nowFloderPath,nowPath);
	strcat(nowFloderPath,"\\*");
	h = FindFirstFileA(nowFloderPath,&stFD);	//构建目录句柄
	while(FindNextFileA(h, &stFD)) {
		if (!strcmp(stFD.cFileName, "..")) {
			continue;
		}
		if (stFD.dwFileAttributes == 0x10) {		//标志位是目录
			char childDir[FILENAMELEN];
			memset(childDir, 0x00, FILENAMELEN);
			strcpy(childDir, nowDirPath);
			strcat(childDir,"\\");
			strcat(childDir, stFD.cFileName);
			getAllFile(childDir);
		}
		else {
			//0x80是普通文件
			if(stFD.dwFileAttributes==0x80){
//				printf("%s\n", stFD.cFileName);
				char* filePath = (char*)malloc(FILENAMELEN);
				memset(filePath, 0x00, FILENAMELEN);
				strcpy(filePath, nowPath);
				strcat(filePath, "\\");
				strcat(filePath, stFD.cFileName);
				readCsv(filePath);
			}
		}
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值