<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def write_bag_file(self, path, encoding=ENCODING):
 # type: (Text, Optional[str]) -> IO """Write the bag file into our research object."""

        self.self_check()
        # For some reason below throws BlockingIOError
        #fp = BufferedWriter(WritableBagFile(self, path))
        bag_file = cast(IO, WritableBagFile(self, path))
        if encoding is not None:
            # encoding: match Tag-File-Character-Encoding: UTF-8
            # newline: ensure LF also on Windows
            return cast(IO,
                        TextIOWrapper(bag_file, encoding=encoding, newline="\n"))
        return bag_file