diff --git a/flopy/utils/binaryfile.py b/flopy/utils/binaryfile.py index a669a8a20..5dc6b26d8 100644 --- a/flopy/utils/binaryfile.py +++ b/flopy/utils/binaryfile.py @@ -638,7 +638,10 @@ def __init__( def reverse(self, filename: Optional[os.PathLike] = None): """ - Write a new binary file with the records in reverse order. + Write a new binary head file with the records in reverse order. + If a new filename is not provided, or if the filename is the same + as the existing filename, the file will be overwritten and data + reloaded from the rewritten/reversed file. Parameters ---------- @@ -647,6 +650,12 @@ def reverse(self, filename: Optional[os.PathLike] = None): Path of the new reversed binary file to create. """ + filename = ( + Path(filename).expanduser().absolute() + if filename + else self.filename + ) + # header array formats dt = np.dtype( [ @@ -678,7 +687,7 @@ def reverse(self, filename: Optional[os.PathLike] = None): nrecords = self.recordarray.shape[0] # open backward file - with open(filename if filename else self.filename, "wb") as fbin: + with open(filename, "wb") as fbin: # loop over head file records in reverse order for idx in range(nrecords - 1, -1, -1): # load header array @@ -705,6 +714,10 @@ def reverse(self, filename: Optional[os.PathLike] = None): data = np.array(data, dtype=np.float64) data.tofile(fbin) + # if we rewrote the original file, reinitialize + if not filename or filename == self.filename: + super().__init__(self.filename, self.precision, self.verbose) + class UcnFile(BinaryLayerFile): """ @@ -2025,7 +2038,10 @@ def close(self): def reverse(self, filename: Optional[os.PathLike] = None): """ - Write a new binary cell budget file with the records in reverse order. + Write a binary cell budget file with the records in reverse order. + If a new filename is not provided, or if the filename is the same + as the existing filename, the file will be overwritten and data + reloaded from the rewritten/reversed file. Parameters ---------- @@ -2034,6 +2050,12 @@ def reverse(self, filename: Optional[os.PathLike] = None): Path of the new reversed binary cell budget file to create. """ + filename = ( + Path(filename).expanduser().absolute() + if filename + else self.filename + ) + # header array formats dt1 = np.dtype( [ @@ -2078,7 +2100,7 @@ def reverse(self, filename: Optional[os.PathLike] = None): nrecords = self.get_nrecords() # open backward budget file - with open(filename, "wb") as fbin: + with open(filename if filename else self.filename, "wb") as fbin: # loop over budget file records in reverse order for idx in range(nrecords - 1, -1, -1): # load header array @@ -2165,6 +2187,10 @@ def reverse(self, filename: Optional[os.PathLike] = None): # Write data data.tofile(fbin) + # if we rewrote the original file, reinitialize + if not filename or (filename == self.filename): + self.__init__(self.filename, self.precision, self.verbose) + class HeadUFile(BinaryLayerFile): """