Python File ZIP dengan Contoh

โšก Ringkasan Cerdas

Python creates ZIP archives with the built-in shutil and zipfile modules. Here you will learn to zip an entire directory using make_archive(), zip specific files with ZipFile, and extract, list, and read archive contents.

  • ๏ธ make_archive(): shutil.make_archive() zips an entire directory into a .zip file.
  • ๐Ÿ“„ ZipFile.write(): ZipFile.write() adds specific files to an archive one by one.
  • ๐Ÿ“‚ extractall(): ZipFile.extractall() unzips every file from an archive to a folder.
  • ๐Ÿ“‹ namelist(): ZipFile.namelist() lists the file names inside a ZIP archive.
  • ๐Ÿค– Bantuan AI: AI tools like Copilot generate zip and unzip code instantly.

Python File ZIP

Python memungkinkan Anda membuat arsip zip/tar dengan cepat.

Perintah berikut akan menzip seluruh direktori

shutil.make_archive(output_filename, 'zip', dir_name)

Perintah berikut memberi Anda kendali atas file yang ingin Anda arsipkan

ZipFile.write(filename)

How to Zip an Entire Directory in Python

Berikut langkah-langkah membuat File Zip Python

Langkah 1) Untuk membuat file arsip dari Python, pastikan Anda memiliki pernyataan impor yang benar dan sesuai urutan. Berikut pernyataan impor untuk arsip tersebut from shutil import make_archive

Python File ZIP

Code Penjelasan

  • Impor kelas make_archive dari modul shutil
  • Gunakan fungsi split untuk memisahkan direktori dan nama file dari jalur ke lokasi file teks (guru99)
  • Kemudian kita panggil modul โ€œshutil.make_archive(โ€œguru99 archive, โ€œzipโ€, root_dir)โ€ untuk membuat file arsip, yang akan berformat zip
  • Setelah itu kita memasukkan direktori root dari hal-hal yang ingin kita zip. Jadi semua yang ada di direktori akan di-zip
  • Ketika Anda menjalankan kode, Anda dapat melihat file zip arsip dibuat di sisi kanan panel.

Langkah 2) Setelah file arsip Anda dibuat, Anda dapat mengklik kanan pada file tersebut dan memilih OS, dan itu akan menampilkan file arsip Anda di dalamnya seperti yang ditunjukkan di bawah ini

Python File ZIP

Sekarang file archive.zip Anda akan muncul di OS Anda (Windows Penjelajah)

Python File ZIP

Langkah 3) Ketika Anda mengklik dua kali pada berkas tersebut, Anda akan melihat daftar semua berkas di sana.

Python File ZIP

How to Zip Specific Files Using ZipFile

Langkah 4) In Python kita dapat memiliki kontrol lebih terhadap arsip karena kita dapat menentukan file spesifik mana yang akan dimasukkan ke dalam arsip. Dalam kasus kita, kita akan memasukkan dua file ke dalam arsip โ€œguru99.txtโ€ ke โ€œguru99.txt.bakโ€.

Python File ZIP

Code Penjelasan

  • Impor kelas Zipfile dari file zip Python modul. Modul ini memberikan kontrol penuh atas pembuatan file zip
  • Kami membuat Zipfile baru dengan nama ( โ€œtestguru99.zip, โ€œwโ€)
  • Membuat kelas Zipfile baru, memerlukan izin karena ini adalah file, jadi Anda perlu menulis informasi ke dalam file sebagai newzip
  • Kami menggunakan variabel "newzip" untuk merujuk ke file zip yang kami buat
  • Dengan menggunakan fungsi tulis pada variabel โ€œnewzipโ€, kita menambahkan file โ€œguru99.txtโ€ dan โ€œguru99.txt.bakโ€ ke dalam arsip

Saat Anda menjalankan kode, Anda dapat melihat file dibuat di sisi kanan panel dengan nama โ€œguru99.zipโ€

Note: Di sini kami tidak memberikan perintah apa pun untuk โ€œmenutupโ€ file seperti โ€œnewzip.closeโ€ karena kami menggunakan kunci cakupan โ€œDenganโ€, jadi ketika program berada di luar cakupan ini, file akan dibersihkan dan ditutup secara otomatis.

Langkah 5) Bila Anda -> klik kanan pada file (testguru99.zip) dan -> pilih OS Anda (Windows Penjelajah), ini akan menampilkan file arsip dalam folder seperti yang ditunjukkan di bawah ini.

Python File ZIP

Ketika Anda mengklik dua kali pada file โ€œtestguru99.zipโ€, maka akan terbuka jendela lain yang akan menampilkan file-file yang ada di dalamnya.

Python File ZIP

Menyelesaikan Python Code to Create a ZIP File

Berikut kode lengkapnya

Python 2 Contoh

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 Contoh

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")

How to Extract (Unzip) a ZIP File in Python

To unzip an archive, open it in read mode with ZipFile and call extractall() to extract every file, or extract() to pull out a single member.

from zipfile import ZipFile

with ZipFile("testguru99.zip", "r") as myzip:
    myzip.extractall("extracted_files")

Sang mantantractall() method writes all the archived files into the folder you pass as an argument.

How to List Files in a ZIP Archive

You can inspect an archive without extracting it. The namelist() method returns the names of every file stored inside the ZIP.

from zipfile import ZipFile

with ZipFile("testguru99.zip", "r") as myzip:
    print(myzip.namelist())

This prints a list of the file names contained in the archive.

How to Read a File Inside a ZIP Archive

You can read a member file directly from the archive without unzipping it to disk using the open() method of ZipFile.

from zipfile import ZipFile

with ZipFile("testguru99.zip", "r") as myzip:
    with myzip.open("guru99.txt") as f:
        print(f.read())

This is useful when you only need the contents of one file from a large archive.

Pertanyaan Umum Demo Slot

Use shutil.make_archive(name, โ€˜zipโ€™, root_dir) to zip a directory, or open a ZipFile in write mode and call write() to add specific files to the archive.

shutil.make_archive() zips a whole directory in one call, while zipfile.ZipFile gives finer control, letting you add, read, or extract individual files within the archive.

Open the archive with ZipFile(โ€˜file.zipโ€™, โ€˜rโ€™) and call extractall(โ€˜folderโ€™) to extract everything, or extract(โ€˜nameโ€™) to pull out a single file from the archive.

Open the ZipFile in read mode and call namelist(), which returns a list of every file name stored in the archive without extracting any of them.

The with statement automatically closes the archive when the block ends, even if an error occurs, so you do not need to call close() manually.

AI assistants like GitHub Copilot autocomplete ZipFile and make_archive() calls, and generate loops that zip or unzip many files from a plain-language description.

Yes. AI-powered tools can automate writing backup and archive scripts, choose between shutil and zipfile, and add error handling for missing files or corrupt archives.

Yes. Open the ZipFile, then use its open() method on a member file to read its contents directly, without extracting the whole archive to disk.

Ringkaslah postingan ini dengan: