1. 개요
- 목적 : 파이썬을 이용한 파일 압축/압축 풀기 프로그램 만들기
- 난이도 : 하
- 사용 라이브러리 : zipfile, sys, os
2. 준비
- python3
- linux 환경
3. 코드 작성
1.
우선 만들고자 하는 프로그램을 정의하자면 다음과 같다.
'zip.py [디렉터리명]' 명령어를 통해 해당 디렉터리 하위 파일에 대한 압축을 수행하여 '디렉터리.zip' 을 생성하고
'unzip.py [zip파일명]' 명령어를 통해 해당 zip파일 압축을 풀어 동일 파일명의 디렉터리를 생성한다.
2.
먼저 압축 프로그램(zip.py)를 만들어보자.
zipfile 라이브러리를 통해 압축파일을 write하기위해서는 대상 파일들의 모든 파일 '경로'가 필요하다.
이에 압축하고자 하는 디렉터리의 모든 파일에 대한 파일 경로를 가져오는 작업이 선행되어야 한다.
3.
모든파일의 경로를 가져오는 함수를 만들자.
이를 위해 os.walk 함수를 이용해야 하는데 이를 먼저 간단하게 정리하고 진행하자.
os.walk 함수는 3-tuple의 집합을 반환하며(dirpath, dirnames, filenames)
dirpath 진입한 디렉토리명, dirnames는 내부 디렉토리 리스트, firenames는 내부 파일 리스트이다.
만약 다음과 같은 디렉터리 트리가 있다고 가정해보자.
└─$ tree kim
kim
├── a.txt
├── b.txt
└── c
├── d.txt
└── e.txt
이에 대한 os.walk의 결과는 다음과 같다.
>>> walked_obj = os.walk("./kim")
>>> for items in walked_obj :
... print(items)
('./kim', ['c'], ['a.txt', 'b.txt'])
('./kim/c', [], ['d.txt', 'e.txt'])
또한 os.path.join 함수를 이용하여 모든 파일에 대한 경로를 가져올 수 있다.
for root, directories, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
print(filepath)
###### print #######
./kim/a.txt
./kim/b.txt
./kim/c/d.txt
./kim/c/e.txt
이를 이용해 작성된 함수는 다음과 같다.
def get_all_file_paths(directory):
file_paths = [] #list for file_paths
for root, directories, files in os.walk(directory): # walk through the directory using os.walk func
for filename in files:
filepath = os.path.join(root, filename) # get full filepath
file_paths.append(filepath)
return file_paths # returning all file paths
4.
그 다음은 main 함수를 작성하여 zip.py를 완성한다.
sys 라이브러리를 이용하여 argv[1] 인자를 가져와서 zipfile 함수에 'w' 인자를 주고 write한다.
import zipfile
import sys
import os
def get_all_file_paths(directory):
file_paths = [] #list for file_paths
for root, directories, files in os.walk(directory): # walk through the directory using os.walk func
for filename in files:
filepath = os.path.join(root, filename) # get full filepath
file_paths.append(filepath)
return file_paths # returning all file paths
def main():
# path to folder which needs to be zipped
target = sys.argv[1]
directory = './' + target
file_paths = get_all_file_paths(directory) #get all file path
print('Following files will be zipped:') #list files which will be zipped
for file_name in file_paths:
print(file_name)
with zipfile.ZipFile(target+'.zip','w') as zip: # write files to a zipfile
for file in file_paths:
zip.write(file)
print('All files zipped successfully!')
if __name__ == "__main__":
main()
이를 통해 zip 하면 다음과 같다.
└─$ python3 zip.py kim
Following files will be zipped:
./kim/a.txt
./kim/b.txt
./kim/c/d.txt
./kim/c/e.txt
All files zipped successfully!
5.
다음은 unzip.py를 작성해보자.
unzip은 extractAll 함수를 통해 다음과 같이 간단히 작성될 수 있다. (zip 암호는 없다고 가정)
import zipfile
import sys
def main():
target = sys.argv[1]
zip_name = './' + target #path of zipfile which should be unzipped
try:
with zipfile.ZipFile(zip_name,'r') as zip: # write files to a zipfile
zip.extractall()
print('Zip file unzipped successfully!')
except Exception as e :
print(e)
if __name__ == "__main__":
main()
실행하면 다음과 같다.
└─$ python3 unzip.py kim.zip
Zip file unzipped successfully!
[참고] https://www.geeksforgeeks.org/working-zip-files-python/
'Software Engineering > Python' 카테고리의 다른 글
파이썬를 이용한 Unix password cracker 만들기 (1) | 2022.04.22 |
---|---|
파이썬 데이터조작 cheet sheet (0) | 2022.04.20 |
댓글