산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> python

예제가 있는 Python ZIP 파일

Python을 사용하면 zip/tar 아카이브를 빠르게 만들 수 있습니다.

다음 명령은 전체 디렉토리를 압축합니다.

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

다음 명령을 사용하면 보관하려는 파일을 제어할 수 있습니다.

ZipFile.write(filename)

다음은 Python에서 Zip 파일을 만드는 단계입니다.

1단계) Python에서 아카이브 파일을 생성하려면 import 문이 정확하고 순서대로 되어 있는지 확인하십시오. 여기서 아카이브에 대한 가져오기 문은 from shutil import make_archive입니다.

코드 설명

2단계) 아카이브 파일이 만들어지면 파일을 마우스 오른쪽 버튼으로 클릭하고 OS를 선택하면 아래와 같이 아카이브 파일이 표시됩니다.

이제 archive.zip 파일이 OS(Windows 탐색기)에 나타납니다.

3단계) 파일을 더블 클릭하면 그 안에 있는 모든 파일의 목록을 볼 수 있습니다.

4단계) Python에서는 아카이브에 포함할 특정 파일을 정의할 수 있으므로 아카이브를 더 많이 제어할 수 있습니다. 우리의 경우 아카이브 “guru99.txt” 아래에 두 개의 파일을 포함합니다. 및 "guru99.txt.bak".

코드 설명

코드를 실행하면 패널 오른쪽에 "guru99.zip"이라는 이름으로 파일이 생성되는 것을 볼 수 있습니다.

참고 :여기에서는 "With" 범위 잠금을 사용하기 때문에 "newzip.close"와 같은 파일을 "닫는" 명령을 제공하지 않습니다. 따라서 프로그램이 이 범위를 벗어나면 파일이 정리되고 자동으로 닫힙니다.

5단계) -> 파일(testguru99.zip)을 마우스 오른쪽 버튼으로 클릭하고 -> OS(Windows 탐색기)를 선택하면 , 아래와 같이 폴더에 아카이브 파일이 표시됩니다.

"testguru99.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()

파이썬 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")

요약


python

  1. 파이썬 파일 I/O
  2. Java BufferedReader:예제를 사용하여 Java에서 파일을 읽는 방법
  3. EXAMPLE이 있는 Python String strip() 함수
  4. 예제가 있는 Python 문자열 count()
  5. 예제가 있는 Python round() 함수
  6. 예제가 있는 Python map() 함수
  7. 예제가 있는 Python Timeit()
  8. 예제가 있는 컬렉션의 Python 카운터
  9. 예제가 있는 Python 목록 count()
  10. 예제가 있는 Python 목록 index()