Skip to content
This repository was archived by the owner on May 25, 2022. It is now read-only.

Commit b90c2b9

Browse files
authored
Merge pull request #84 from Xlgd/master
#60 fixed
2 parents dcb0623 + d7d29ee commit b90c2b9

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
## write script to compress folder and files
2+
3+
### usage
4+
5+
python zipfiles.py file_name(or folder name)
6+
7+
example:
8+
python zipfiles.py test.txt
9+
python zipfiles.py ./test (folder)
10+
11+
A Compressed file("filename.zip") will be generated after the program is run
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import zipfile
2+
import sys
3+
import os
4+
5+
6+
# compress file function
7+
def zip_file(file_path):
8+
compress_file = zipfile.ZipFile(file_path + '.zip', 'w')
9+
compress_file.write(path, compress_type=zipfile.ZIP_DEFLATED)
10+
compress_file.close()
11+
12+
13+
# Declare the function to return all file paths of the particular directory
14+
def retrieve_file_paths(dir_name):
15+
# setup file paths variable
16+
file_paths = []
17+
18+
# Read all directory, subdirectories and file lists
19+
for root, directories, files in os.walk(dir_name):
20+
for filename in files:
21+
# Create the full file path by using os module.
22+
file_path = os.path.join(root, filename)
23+
file_paths.append(file_path)
24+
25+
# return all paths
26+
return file_paths
27+
28+
29+
def zip_dir(dir_path, file_paths):
30+
# write files and folders to a zipfile
31+
compress_dir = zipfile.ZipFile(dir_path + '.zip', 'w')
32+
with compress_dir:
33+
# write each file separately
34+
for file in file_paths:
35+
compress_dir.write(file)
36+
37+
38+
if __name__ == "__main__":
39+
path = sys.argv[1]
40+
41+
if os.path.isdir(path):
42+
files_path = retrieve_file_paths(path)
43+
# print the list of files to be zipped
44+
print('The following list of files will be zipped:')
45+
for file_name in files_path:
46+
print(file_name)
47+
zip_dir(path, files_path)
48+
elif os.path.isfile(path):
49+
print('The %s will be zipped:' % path)
50+
zip_file(path)
51+
else:
52+
print('a special file(socket,FIFO,device file), please input file or dir')

0 commit comments

Comments
 (0)