@@ -1041,6 +1041,7 @@ def to_file(
10411041 self ,
10421042 path : PathLike [str ] | str ,
10431043 mode : Literal ["w" , "x" ] = "w" ,
1044+ compression : Compression | str | None = None ,
10441045 ) -> None :
10451046 """
10461047 Write the data to a DBN file at the given path.
@@ -1051,6 +1052,8 @@ def to_file(
10511052 The file path to write to.
10521053 mode : str, default "w"
10531054 The file write mode to use, either "x" or "w".
1055+ compression : Compression or str, optional
1056+ The compression format to write. If `None`, uses the same compression as the underlying data.
10541057
10551058 Raises
10561059 ------
@@ -1062,9 +1065,35 @@ def to_file(
10621065 If path is not writable.
10631066
10641067 """
1068+ compression = validate_maybe_enum (compression , Compression , "compression" )
10651069 file_path = validate_file_write_path (path , "path" , exist_ok = mode == "w" )
1066- file_path .write_bytes (self ._data_source .reader .read ())
1067- self ._data_source = FileDataSource (file_path )
1070+
1071+ writer : IO [bytes ] | zstandard .ZstdCompressionWriter
1072+ if compression is None or compression == self .compression :
1073+ # Handle trivial case
1074+ with open (file_path , mode = f"{ mode } b" ) as writer :
1075+ reader = self ._data_source .reader
1076+ while chunk := reader .read (2 ** 16 ):
1077+ writer .write (chunk )
1078+ return
1079+
1080+ if compression == Compression .ZSTD :
1081+ writer = zstandard .ZstdCompressor (
1082+ write_checksum = True ,
1083+ ).stream_writer (
1084+ open (file_path , mode = f"{ mode } b" ),
1085+ closefd = True ,
1086+ )
1087+ else :
1088+ writer = open (file_path , mode = f"{ mode } b" )
1089+
1090+ try :
1091+ reader = self .reader
1092+
1093+ while chunk := reader .read (2 ** 16 ):
1094+ writer .write (chunk )
1095+ finally :
1096+ writer .close ()
10681097
10691098 def to_json (
10701099 self ,
0 commit comments