Write data to the file. There is no return value. `data` can be either a string of bytes or a file-like object (implementing :meth:`read`). If the file has an :attr:`encoding` attribute, `data` can also be a :class:`str` instance, which will be encoded as :at
(self, data: Any)
| 1336 | return False |
| 1337 | |
| 1338 | async def write(self, data: Any) -> None: |
| 1339 | """Write data to the file. There is no return value. |
| 1340 | |
| 1341 | `data` can be either a string of bytes or a file-like object |
| 1342 | (implementing :meth:`read`). If the file has an |
| 1343 | :attr:`encoding` attribute, `data` can also be a |
| 1344 | :class:`str` instance, which will be encoded as |
| 1345 | :attr:`encoding` before being written. |
| 1346 | |
| 1347 | Due to buffering, the data may not actually be written to the |
| 1348 | database until the :meth:`close` method is called. Raises |
| 1349 | :class:`ValueError` if this file is already closed. Raises |
| 1350 | :class:`TypeError` if `data` is not an instance of |
| 1351 | :class:`bytes`, a file-like object, or an instance of :class:`str`. |
| 1352 | Unicode data is only allowed if the file has an :attr:`encoding` |
| 1353 | attribute. |
| 1354 | |
| 1355 | :param data: string of bytes or file-like object to be written |
| 1356 | to the file |
| 1357 | """ |
| 1358 | if self._closed: |
| 1359 | raise ValueError("cannot write to a closed file") |
| 1360 | |
| 1361 | try: |
| 1362 | # file-like |
| 1363 | read = data.read |
| 1364 | except AttributeError: |
| 1365 | # string |
| 1366 | if not isinstance(data, (str, bytes)): |
| 1367 | raise TypeError("can only write strings or file-like objects") from None |
| 1368 | if isinstance(data, str): |
| 1369 | try: |
| 1370 | data = data.encode(self.encoding) |
| 1371 | except AttributeError: |
| 1372 | raise TypeError( |
| 1373 | "must specify an encoding for file in order to write str" |
| 1374 | ) from None |
| 1375 | read = io.BytesIO(data).read |
| 1376 | |
| 1377 | if inspect.iscoroutinefunction(read): |
| 1378 | await self._write_async(read) |
| 1379 | else: |
| 1380 | if self._buffer.tell() > 0: |
| 1381 | # Make sure to flush only when _buffer is complete |
| 1382 | space = self.chunk_size - self._buffer.tell() |
| 1383 | if space: |
| 1384 | try: |
| 1385 | to_write = read(space) |
| 1386 | except BaseException: |
| 1387 | await self.abort() |
| 1388 | raise |
| 1389 | self._buffer.write(to_write) |
| 1390 | if len(to_write) < space: |
| 1391 | return # EOF or incomplete |
| 1392 | await self._flush_buffer() |
| 1393 | to_write = read(self.chunk_size) |
| 1394 | while to_write and len(to_write) == self.chunk_size: |
| 1395 | await self._flush_data(to_write) |