import zipfile
import os
1. 압축하기
1-1. 개별파일 압축하기 : zip객체.write()
텍스트파일을 open해 ‘w’모드로 쓰는 것과 마찬가지로 zip파일을 만들고 그 안에 압축할 파일들을 쓰는(write) 방식으로 사용한다.
my_zip = zipfile.ZipFile("C:/Users/User/Desktop/test_zip.zip", 'w') # zip파일 쓰기모드
my_zip.write('C:/Users/User/Desktop/test1.txt') # 압축할 파일 write
my_zip.close() # zip파일 close
하지만 이렇게 하면 파일만 압축하는게 아니라, 그 모든 경로들을 전부 압축해버리기 때문에 작업디렉토리를 이동해서 작업하는 게 좋다.
os.chdir("C:/Users/User/Desktop/")
my_zip = zipfile.ZipFile("test_zip.zip", 'w')
my_zip.write('test1.txt')
my_zip.close()
1-2. 여러파일 압축하기 : for문 zip객체.write()
여러파일을 압축하려면 위와 같은 방식으로 진행하되 그냥 for문으로 write해주기만 하면된다.
이번에는 with문을 이용해보자.
file_ls = ['test1.txt', 'test2.txt', 'test3.txt', 'testtest.csv']
with zipfile.ZipFile("test_zip.zip", 'w') as my_zip:
for i in file_ls:
my_zip.write(i)
my_zip.close()
4개의 파일이 test_zip이라는 압축파일로 압축된 것을 알 수 있다.
2. 압축해제
2-1. 개별파일 압축해제 : extract()
extract(압축해제할 파일명, 압축해제할 경로) 로 이용하며, 압축파일 안에서도 파일을 골라서 압축해제 할 수 있다.
zipfile.ZipFile('test_zip.zip').extract('test1.txt')
[Output]
'C:\\Users\\User\\Desktop\\test1.txt'
경로를 반환해주고, 해당파일 압축을 해제한 것을 알 수 있다.
2-2. 모든파일 압축해제 : extractall()
extractall(압축해제할 경로)로 이용되며, 해당 압축파일을 해당 경로에 모두 압축해제를 시켜준다.
당연히 경로를 지정하지 않으면, 현재 작업디렉토리에 바로 압축이 해제된다.
zipfile.ZipFile('test_zip.zip').extractall()
3. zip파일 읽기
3-1. 특정 파일 읽기 : read()
read()함수는 해당 파일을 읽어주는
my_zip = zipfile.ZipFile('test_zip.zip')
my_zip.read('testtest.csv')
[Output]
b'no,value\r\ntest1,1\r\ntest2,2\r\ntest3,3\r\ntest4,4\r\n'
참고로 testtest.csv 파일은 아래와 같이 생긴 파일이다.
print(pd.read_csv('testtest.csv', sep=','))
[Output]
no value
0 test1 1
1 test2 2
2 test3 3
3 test4 4
*read()함수는 인코딩과 디코딩의 개념을 통해 더 자세한 응용이 가능해지나 이 부분은 추후에 포스팅 할 예정이다.
3-2. 압축파일 내 파일명 읽기 : namelist()
압축파일 내에 존재하는 파일명을 리스트로 반환해주는 함수로, 유용하게 사용된다.
my_zip = zipfile.ZipFile('test_zip.zip')
my_zip.namelist()
[Output]
['test1.txt', 'test2.txt', 'test3.txt', 'testtest.csv']
3-3. 압축파일정보 확인 : getinfo()
getinfo()함수는 압축파일 내에 들어 있는 개별 파일의 정보를 읽을 수 있게 도와주는 함수이다.
Zipinfo객체를 반환하는데, 이 객체는 다양한 정보들을 지니고 있다.
zp_info = my_zip.getinfo('testtest.csv') # csv파일의 Zipinfo객체 생성
print(zp_info.filename) # 파일명
print(zp_info.file_size) # 파일용량
print(zp_info.date_time) # 작성일자
print(zp_info.compress_size)
print(zp_
'파일 관리 - 이미지 처리 - pdf' 카테고리의 다른 글
exe 실행파일 만들기 (0) | 2022.10.09 |
---|---|
Pillow 총 정리 (0) | 2022.10.09 |
픽셀과 dpi (0) | 2022.10.08 |
img2pdf, os.path (0) | 2022.10.08 |
자작 1) 양면 합치기 /좌우바꿈(일본만화식)/ (0) | 2022.10.08 |
캡처 매크로 (0) | 2022.10.05 |
img to pdf ( pprint ) (0) | 2022.09.23 |
zip to pdf ( img2pdf, zipfile, os, glob, shutil ) (0) | 2022.09.23 |
댓글