logo

Python에서 zip 파일 작업

이 기사에서는 간단한 Python 프로그램을 사용하여 zip 파일에 대해 다양한 작업을 수행하는 방법을 설명합니다. zip 파일이란 무엇입니까? ZIP은 무손실 데이터 압축을 지원하는 아카이브 파일 형식입니다. 무손실 압축이란 압축 알고리즘을 통해 압축된 데이터에서 원본 데이터를 완벽하게 재구성할 수 있음을 의미합니다. 따라서 ZIP 파일은 하나 이상의 압축 파일이 포함된 단일 파일로, 큰 파일을 더 작게 만들고 관련 파일을 함께 보관하는 이상적인 방법을 제공합니다. zip 파일이 필요한 이유는 무엇입니까?
  • 스토리지 요구 사항을 줄입니다.
  • 표준 연결을 통해 전송 속도를 향상합니다.
Python을 사용하여 zip 파일 작업을 하려면 내장된 Python 모듈인 Python을 사용합니다. zip 파일 .

1. zip 파일 추출

Python
# importing required modules from zipfile import ZipFile # specifying the zip file name file_name = 'my_python_files.zip' # opening the zip file in READ mode with ZipFile(file_name 'r') as zip: # printing all the contents of the zip file zip.printdir() # extracting all the files print('Extracting all the files now...') zip.extractall() print('Done!') 
The above program extracts a zip file named 'my_python_files.zip' in the same directory as of this python script. The output of above program may look like this: Python에서 zip 파일 작업' title=위의 코드를 부분적으로 이해해 보겠습니다.
  • from zipfile import ZipFile
    ZipFile is a class of zipfile module for reading and writing zip files. Here we import only class ZipFile from zipfile module.
  • with ZipFile(file_name 'r') as zip:
    Here a ZipFile object is made by calling ZipFile constructor which accepts zip file name and mode parameters. We create a ZipFile object in 읽다 모드를 지정하고 이름을 다음과 같이 지정합니다. 지퍼 .
  • zip.printdir()
    인쇄디렉터리() 메소드는 아카이브의 목차를 인쇄합니다.
  • zip.extractall()
    추출() 메서드는 zip 파일의 모든 내용을 현재 작업 디렉터리로 추출합니다. 당신은 또한 전화할 수 있습니다 발췌() method to extract any file by specifying its path in the zip file. For example:
    zip.extract('python_files/python_wiki.txt')
    This will extract only the specified file. If you want to read some specific file you can go like this:
    data = zip.read(name_of_file_to_read)

2. zip 파일에 쓰기

다음과 같은 형식의 디렉터리(폴더)를 생각해 보세요. Python에서 zip 파일 작업' title= Here we will need to crawl the whole directory and its sub-directories in order to get a list of all file paths before writing them to a zip file. The following program does this by crawling the directory to be zipped: Python
# importing required modules from zipfile import ZipFile import os def get_all_file_paths(directory): # initializing empty file paths list file_paths = [] # crawling through directory and subdirectories for root directories files in os.walk(directory): for filename in files: # join the two strings in order to form the full filepath. filepath = os.path.join(root filename) file_paths.append(filepath) # returning all file paths return file_paths def main(): # path to folder which needs to be zipped directory = './python_files' # calling function to get all file paths in the directory file_paths = get_all_file_paths(directory) # printing the list of all files to be zipped print('Following files will be zipped:') for file_name in file_paths: print(file_name) # writing files to a zipfile with ZipFile('my_python_files.zip''w') as zip: # writing each file one by one for file in file_paths: zip.write(file) print('All files zipped successfully!') if __name__ == '__main__': main() 
The output of above program looks like this: Python에서 zip 파일 작업' title=위의 코드를 조각으로 나누어 이해해 보겠습니다.
  • def get_all_file_paths(directory): file_paths = [] for root directories files in os.walk(directory): for filename in files: filepath = os.path.join(root filename) file_paths.append(filepath) return file_paths
    First of all to get all file paths in our directory we have created this function which uses the os.walk()  방법. 각 반복에서 해당 디렉토리에 있는 모든 파일은 다음과 같은 목록에 추가됩니다. 파일_경로 . 결국 우리는 모든 파일 경로를 반환합니다.
  • file_paths = get_all_file_paths(directory)
    Here we pass the directory to be zipped to the get_all_file_paths() 기능을 수행하고 모든 파일 경로가 포함된 목록을 얻습니다.
  • with ZipFile('my_python_files.zip''w') as zip:
    Here we create a ZipFile object in WRITE mode this time.
  • for file in file_paths: zip.write(file)
    Here we write all the files to the zip file one by one using 쓰다 방법.

3. zip 파일에 대한 모든 정보 얻기



Python
# importing required modules from zipfile import ZipFile import datetime # specifying the zip file name file_name = 'example.zip' # opening the zip file in READ mode with ZipFile(file_name 'r') as zip: for info in zip.infolist(): print(info.filename) print('tModified:t' + str(datetime.datetime(*info.date_time))) print('tSystem:tt' + str(info.create_system) + '(0 = Windows 3 = Unix)') print('tZIP version:t' + str(info.create_version)) print('tCompressed:t' + str(info.compress_size) + ' bytes') print('tUncompressed:t' + str(info.file_size) + ' bytes') 
The output of above program may look like this: ' title=
for info in zip.infolist():
Here 정보 목록() 메소드는 다음의 인스턴스를 생성합니다. 우편번호정보 zip 파일에 대한 모든 정보를 포함하는 클래스입니다. 파일이 생성된 파일 이름 시스템의 마지막 수정 날짜와 같은 모든 정보에 액세스할 수 있습니다. 압축 및 압축되지 않은 형식의 파일의 Zip 버전 크기 등. 이 문서는 에서 제공되었습니다. 니킬 쿠마르 . 퀴즈 만들기