Python 예제가 포함된 ZIP 파일
⚡ 스마트 요약
Python 이 프로그램은 내장된 `make_archive` 및 `zipfile` 모듈을 사용하여 ZIP 아카이브를 생성합니다. 여기서는 `make_archive()`를 사용하여 전체 디렉토리를 압축하고, `zipFile`을 사용하여 특정 파일만 압축하는 방법을 배웁니다.tract, 목록, 그리고 아카이브 내용 읽기.

Python zip/tar 아카이브를 빠르게 생성할 수 있습니다.
다음 명령은 전체 디렉토리를 압축합니다.
shutil.make_archive(output_filename, 'zip', dir_name)
다음 명령을 사용하면 보관하려는 파일을 제어할 수 있습니다.
ZipFile.write(filename)
전체 디렉토리를 압축하는 방법 Python
다음은 Zip 파일을 생성하는 단계입니다. Python
단계 1) 아카이브 파일을 생성하려면 Python, 가져오기 진술이 올바르고 순서대로 되어 있는지 확인하십시오. 여기서 아카이브에 대한 가져오기 진술은 다음과 같습니다. from shutil import make_archive
Code 설명
- 모듈 shutil에서 make_archive 클래스를 가져옵니다.
- 분할 기능을 사용하여 경로에서 텍스트 파일(guru99) 위치까지 디렉터리와 파일 이름을 분할합니다.
- 그런 다음 모듈 "shutil.make_archive("guru99 archive, "zip", root_dir)"를 호출하여 zip 형식이 될 아카이브 파일을 생성합니다.
- 그런 다음 압축하려는 항목의 루트 디렉터리를 전달합니다. 따라서 디렉토리의 모든 내용은 압축됩니다.
- 코드를 실행하면 패널 오른쪽에 보관된 zip 파일이 생성된 것을 볼 수 있습니다.
단계 2) 보관 파일이 만들어지면 파일을 마우스 오른쪽 버튼으로 클릭하고 OS를 선택하면 아래와 같이 보관 파일이 표시됩니다.
이제 archive.zip 파일이 OS에 나타납니다.Windows 탐색기)
단계 3) 파일을 두 번 클릭하면 해당 파일에 있는 모든 파일 목록이 표시됩니다.
ZipFile을 사용하여 특정 파일만 압축하는 방법
단계 4) In Python 우리는 archive에 포함할 특정 파일을 정의할 수 있기 때문에 archive에 대한 통제력을 더 가질 수 있습니다. 우리의 경우 archive에 두 개의 파일을 포함할 것입니다. “guru99.txt” “guru99.txt.bak”.
Code 설명
- zip 파일에서 Zipfile 클래스 가져오기 Python 기준 치수. 이 모듈은 zip 파일 생성을 완벽하게 제어할 수 있습니다.
- 이름(“testguru99.zip, “w”)으로 새 Zipfile을 생성합니다.
- 새 Zipfile 클래스를 생성하려면 파일이므로 권한을 전달해야 하므로 파일에 정보를 newzip으로 작성해야 합니다.
- 우리가 만든 zip 파일을 참조하기 위해 변수 "newzip"을 사용했습니다.
- “newzip” 변수에 write 함수를 사용하여 “guru99.txt” 및 “guru99.txt.bak” 파일을 아카이브에 추가합니다.
코드를 실행하면 패널 오른쪽에 "guru99.zip"이라는 이름의 파일이 생성되는 것을 볼 수 있습니다.
주의 사항: 여기서는 "With" 범위 잠금을 사용하기 때문에 "newzip.close"와 같은 파일을 "닫는" 명령을 제공하지 않습니다. 따라서 프로그램이 이 범위를 벗어나면 파일이 정리되고 자동으로 닫힙니다.
단계 5) . -> 파일(testguru99.zip)을 마우스 오른쪽 버튼으로 클릭하고 -> OS를 선택합니다(Windows 탐색기), 아래와 같이 폴더의 보관 파일이 표시됩니다.
"testguru99.zip" 파일을 두 번 클릭하면 또 다른 창이 열리고, 여기에 포함된 파일이 표시됩니다.
완료 Python Code ZIP 파일을 생성하려면
다음은 완전한 코드입니다.
Python 2 예
import os
import shutil
from zipfile import ZipFile
from os import path
from shutil import make_archive
def main():
# Check if file exists
if path.exists("guru99.txt"):
# get the path to the file in the current directory
src = path.realpath("guru99.txt");
# rename the original file
os.rename("career.guru99.txt","guru99.txt")
# now put things into a ZIP archive
root_dir,tail = path.split(src)
shutil.make_archive("guru99 archive", "zip", root_dir)
# more fine-grained control over ZIP files
with ZipFile("testguru99.zip","w") as newzip:
newzip.write("guru99.txt")
newzip.write("guru99.txt.bak")
if __name__== "__main__":
main()
Python 3 예
import os import shutil from zipfile import ZipFile from os import path from shutil import make_archive # Check if file exists if path.exists("guru99.txt"): # get the path to the file in the current directory src = path.realpath("guru99.txt"); # rename the original file os.rename("career.guru99.txt","guru99.txt") # now put things into a ZIP archive root_dir,tail = path.split(src) shutil.make_archive("guru99 archive","zip",root_dir) # more fine-grained control over ZIP files with ZipFile("testguru99.zip", "w") as newzip: newzip.write("guru99.txt") newzip.write("guru99.txt.bak")
어떻게 Extract (압축 해제) ZIP 파일 Python
압축 파일을 해제하려면 ZipFile을 사용하여 읽기 모드로 열고 ex를 호출하십시오.tractall()을 ex로trac모든 파일 또는 예tract()를 사용하여 단일 멤버를 추출합니다.
from zipfile import ZipFile with ZipFile("testguru99.zip", "r") as myzip: myzip.extractall("extracted_files")
전tractall() 메서드는 인수로 전달된 폴더에 압축된 모든 파일을 저장합니다.
ZIP 파일의 파일 목록을 확인하는 방법 Archive
별도의 조치 없이 아카이브를 검사할 수 있습니다.tracting it. namelist() 메서드는 ZIP 파일 안에 저장된 모든 파일의 이름을 반환합니다.
from zipfile import ZipFile with ZipFile("testguru99.zip", "r") as myzip: print(myzip.namelist())
이 명령은 압축 파일에 포함된 파일 이름 목록을 출력합니다.
ZIP 파일 안에 있는 파일을 읽는 방법 Archive
압축을 풀지 않고도 아카이브에서 멤버 파일을 직접 읽을 수 있습니다.ping ZipFile의 open() 메서드를 사용하여 디스크에 저장합니다.
from zipfile import ZipFile with ZipFile("testguru99.zip", "r") as myzip: with myzip.open("guru99.txt") as f: print(f.read())
이 기능은 대용량 압축 파일에서 특정 파일 하나의 내용만 필요할 때 유용합니다.







