| 1476 | |
| 1477 | |
| 1478 | class FileIO(RawIOBase): |
| 1479 | _fd = -1 |
| 1480 | _created = False |
| 1481 | _readable = False |
| 1482 | _writable = False |
| 1483 | _appending = False |
| 1484 | _seekable = None |
| 1485 | _closefd = True |
| 1486 | |
| 1487 | def __init__(self, file, mode='r', closefd=True, opener=None): |
| 1488 | """Open a file. The mode can be 'r' (default), 'w', 'x' or 'a' for reading, |
| 1489 | writing, exclusive creation or appending. The file will be created if it |
| 1490 | doesn't exist when opened for writing or appending; it will be truncated |
| 1491 | when opened for writing. A FileExistsError will be raised if it already |
| 1492 | exists when opened for creating. Opening a file for creating implies |
| 1493 | writing so this mode behaves in a similar way to 'w'. Add a '+' to the mode |
| 1494 | to allow simultaneous reading and writing. A custom opener can be used by |
| 1495 | passing a callable as *opener*. The underlying file descriptor for the file |
| 1496 | object is then obtained by calling opener with (*name*, *flags*). |
| 1497 | *opener* must return an open file descriptor (passing os.open as *opener* |
| 1498 | results in functionality similar to passing None). |
| 1499 | """ |
| 1500 | if self._fd >= 0: |
| 1501 | # Have to close the existing file first. |
| 1502 | self._stat_atopen = None |
| 1503 | try: |
| 1504 | if self._closefd: |
| 1505 | os.close(self._fd) |
| 1506 | finally: |
| 1507 | self._fd = -1 |
| 1508 | |
| 1509 | if isinstance(file, float): |
| 1510 | raise TypeError('integer argument expected, got float') |
| 1511 | if isinstance(file, int): |
| 1512 | if isinstance(file, bool): |
| 1513 | import warnings |
| 1514 | warnings.warn("bool is used as a file descriptor", |
| 1515 | RuntimeWarning, stacklevel=2) |
| 1516 | file = int(file) |
| 1517 | fd = file |
| 1518 | if fd < 0: |
| 1519 | raise ValueError('negative file descriptor') |
| 1520 | else: |
| 1521 | fd = -1 |
| 1522 | |
| 1523 | if not isinstance(mode, str): |
| 1524 | raise TypeError('invalid mode: %s' % (mode,)) |
| 1525 | if not set(mode) <= set('xrwab+'): |
| 1526 | raise ValueError('invalid mode: %s' % (mode,)) |
| 1527 | if sum(c in 'rwax' for c in mode) != 1 or mode.count('+') > 1: |
| 1528 | raise ValueError('Must have exactly one of create/read/write/append ' |
| 1529 | 'mode and at most one plus') |
| 1530 | |
| 1531 | if 'x' in mode: |
| 1532 | self._created = True |
| 1533 | self._writable = True |
| 1534 | flags = os.O_EXCL | os.O_CREAT |
| 1535 | elif 'r' in mode: |
no outgoing calls
no test coverage detected