Open the file pointed to by this path and return a file object, as the built-in open() function does.
(path, mode='r', buffering=-1, encoding=None, errors=None,
newline=None)
| 167 | |
| 168 | |
| 169 | def magic_open(path, mode='r', buffering=-1, encoding=None, errors=None, |
| 170 | newline=None): |
| 171 | """ |
| 172 | Open the file pointed to by this path and return a file object, as |
| 173 | the built-in open() function does. |
| 174 | """ |
| 175 | text = 'b' not in mode |
| 176 | if text: |
| 177 | # Call io.text_encoding() here to ensure any warning is raised at an |
| 178 | # appropriate stack level. |
| 179 | encoding = text_encoding(encoding) |
| 180 | try: |
| 181 | return open(path, mode, buffering, encoding, errors, newline) |
| 182 | except TypeError: |
| 183 | pass |
| 184 | cls = type(path) |
| 185 | mode = ''.join(sorted(c for c in mode if c not in 'bt')) |
| 186 | if text: |
| 187 | try: |
| 188 | attr = getattr(cls, f'__open_{mode}__') |
| 189 | except AttributeError: |
| 190 | pass |
| 191 | else: |
| 192 | return attr(path, buffering, encoding, errors, newline) |
| 193 | elif encoding is not None: |
| 194 | raise ValueError("binary mode doesn't take an encoding argument") |
| 195 | elif errors is not None: |
| 196 | raise ValueError("binary mode doesn't take an errors argument") |
| 197 | elif newline is not None: |
| 198 | raise ValueError("binary mode doesn't take a newline argument") |
| 199 | |
| 200 | try: |
| 201 | attr = getattr(cls, f'__open_{mode}b__') |
| 202 | except AttributeError: |
| 203 | pass |
| 204 | else: |
| 205 | stream = attr(path, buffering) |
| 206 | if text: |
| 207 | stream = TextIOWrapper(stream, encoding, errors, newline) |
| 208 | return stream |
| 209 | |
| 210 | raise TypeError(f"{cls.__name__} can't be opened with mode {mode!r}") |
| 211 | |
| 212 | |
| 213 | def ensure_distinct_paths(source, target): |