1
+ import io
1
2
import os
2
3
import shutil
3
4
import zipfile
@@ -44,10 +45,9 @@ def __init__(self, record_name, mode="r"):
44
45
self .zipfile = zipfile .ZipFile (self .archive_path , mode = "r" )
45
46
46
47
elif mode == "w" :
47
- # Initialize an empty archive on disk
48
+ # Create archive file if needed
48
49
if not os .path .exists (self .archive_path ):
49
- with zipfile .ZipFile (self .archive_path , mode = "w" ):
50
- pass # Just create the file
50
+ WFDBArchive .make_archive_file ([], self .archive_path )
51
51
self .zipfile = zipfile .ZipFile (self .archive_path , mode = "a" )
52
52
53
53
def __enter__ (self ):
@@ -62,6 +62,15 @@ def exists(self, filename):
62
62
"""
63
63
return self .zipfile and filename in self .zipfile .namelist ()
64
64
65
+ @staticmethod
66
+ def make_archive_file (file_list , output_path ):
67
+ with zipfile .ZipFile (output_path , mode = "w" ) as zf :
68
+ for file in file_list :
69
+ compress = zipfile .ZIP_DEFLATED
70
+ zf .write (
71
+ file , arcname = os .path .basename (file ), compress_type = compress
72
+ )
73
+
65
74
@contextmanager
66
75
def open (self , filename , mode = "r" ):
67
76
"""
@@ -73,8 +82,6 @@ def open(self, filename, mode="r"):
73
82
if "b" in mode :
74
83
yield f
75
84
else :
76
- import io
77
-
78
85
yield io .TextIOWrapper (f )
79
86
else :
80
87
raise FileNotFoundError (
@@ -97,7 +104,7 @@ def write(self, filename, data):
97
104
self .zipfile .writestr (filename , data )
98
105
return
99
106
100
- # If already opened in read or append mode, use the replace-then-move trick
107
+ # If already opened in read or append mode, use replace-then-move
101
108
tmp_path = self .archive_path + ".tmp"
102
109
with zipfile .ZipFile (self .archive_path , mode = "r" ) as zin :
103
110
with zipfile .ZipFile (tmp_path , mode = "w" ) as zout :
@@ -114,16 +121,13 @@ def create_archive(self, file_list, output_path=None):
114
121
If output_path is not specified, uses self.archive_path.
115
122
"""
116
123
output_path = output_path or self .archive_path
117
- with zipfile .ZipFile (output_path , mode = "w" ) as zf :
118
- for file in file_list :
119
- compress = (
120
- zipfile .ZIP_STORED
121
- if file .endswith ((".hea" , ".hea.json" , ".hea.yml" ))
122
- else zipfile .ZIP_DEFLATED
123
- )
124
- zf .write (
125
- file , arcname = os .path .basename (file ), compress_type = compress
126
- )
124
+ WFDBArchive .make_archive_file (file_list , output_path )
125
+
126
+ # If this archive object points to the archive, reload the zipfile in append mode
127
+ if output_path == self .archive_path :
128
+ if self .zipfile :
129
+ self .zipfile .close ()
130
+ self .zipfile = zipfile .ZipFile (self .archive_path , mode = "a" )
127
131
128
132
129
133
def get_archive (record_base_name , mode = "r" ):
0 commit comments