[PYTHON/COMMON] ZipFile 클래스 : ZIP 파일 압축/압축 해제하기
■ ZipFile 클래스를 사용해 ZIP 파일을 압축하고 압축 해제하는 방법을 보여준다. ▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import zipfile import os def unzip(sourceFilePath, targetDirectoryPath): with zipfile.ZipFile(sourceFilePath, "r") as zipFile: zipFile.extractall(path = targetDirectoryPath) zipFile.close() def zip(sourceDirectoryPath, targetFilePath): with zipfile.ZipFile(targetFilePath, "w") as zipFile: rootDirectoryPath = sourceDirectoryPath for (directory, childDirectoryNameList, childFileNameList) in os.walk(sourceDirectoryPath): for childFileName in childFileNameList: childFilePath = os.path.join(directory, childFileName) relativeChildFilePath = os.path.relpath(childFilePath, rootDirectoryPath); zipFile.write(childFilePath, relativeChildFilePath, zipfile.ZIP_DEFLATED) zipFile.close() if __name__ == "__main__": unzip("./source.zip", "./temp") zip("./temp", "./target.zip") |