|
12 | 12 |
|
13 | 13 |
|
14 | 14 | # Python imports |
| 15 | +import io |
15 | 16 | import os |
16 | 17 | import sys |
17 | 18 | import logging |
18 | 19 | import operator |
19 | 20 | import collections |
20 | | -import io |
21 | 21 | from itertools import chain |
22 | 22 |
|
23 | 23 | # Local imports |
@@ -107,22 +107,6 @@ def get_fixers_from_package(pkg_name): |
107 | 107 | def _identity(obj): |
108 | 108 | return obj |
109 | 109 |
|
110 | | -if sys.version_info < (3, 0): |
111 | | - import codecs |
112 | | - _open_with_encoding = codecs.open |
113 | | - # codecs.open doesn't translate newlines sadly. |
114 | | - def _from_system_newlines(input): |
115 | | - return input.replace("\r\n", "\n") |
116 | | - def _to_system_newlines(input): |
117 | | - if os.linesep != "\n": |
118 | | - return input.replace("\n", os.linesep) |
119 | | - else: |
120 | | - return input |
121 | | -else: |
122 | | - _open_with_encoding = open |
123 | | - _from_system_newlines = _identity |
124 | | - _to_system_newlines = _identity |
125 | | - |
126 | 110 |
|
127 | 111 | def _detect_future_features(source): |
128 | 112 | have_docstring = False |
@@ -330,8 +314,8 @@ def _read_python_source(self, filename): |
330 | 314 | encoding = tokenize.detect_encoding(f.readline)[0] |
331 | 315 | finally: |
332 | 316 | f.close() |
333 | | - with _open_with_encoding(filename, "r", encoding=encoding) as f: |
334 | | - return _from_system_newlines(f.read()), encoding |
| 317 | + with io.open(filename, "r", encoding=encoding) as f: |
| 318 | + return f.read(), encoding |
335 | 319 |
|
336 | 320 | def refactor_file(self, filename, write=False, doctests_only=False): |
337 | 321 | """Refactors a file.""" |
@@ -530,16 +514,16 @@ def write_file(self, new_text, filename, old_text, encoding=None): |
530 | 514 | set. |
531 | 515 | """ |
532 | 516 | try: |
533 | | - f = _open_with_encoding(filename, "w", encoding=encoding) |
| 517 | + fp = io.open(filename, "w", encoding=encoding) |
534 | 518 | except OSError as err: |
535 | 519 | self.log_error("Can't create %s: %s", filename, err) |
536 | 520 | return |
537 | | - try: |
538 | | - f.write(_to_system_newlines(new_text)) |
539 | | - except OSError as err: |
540 | | - self.log_error("Can't write %s: %s", filename, err) |
541 | | - finally: |
542 | | - f.close() |
| 521 | + |
| 522 | + with fp: |
| 523 | + try: |
| 524 | + fp.write(new_text) |
| 525 | + except OSError as err: |
| 526 | + self.log_error("Can't write %s: %s", filename, err) |
543 | 527 | self.log_debug("Wrote changes to %s", filename) |
544 | 528 | self.wrote = True |
545 | 529 |
|
|
0 commit comments