File tree Expand file tree Collapse file tree 1 file changed +22
-11
lines changed Expand file tree Collapse file tree 1 file changed +22
-11
lines changed Original file line number Diff line number Diff line change @@ -224,17 +224,28 @@ def move(
224
224
225
225
226
226
def _replace_in_file (path , expr , replacement ):
227
- with path .open ("r+" ) as fh :
228
- content = fh .read ()
229
- content , count = expr .subn (replacement , content )
230
-
231
- # Don't bother writing the file if we didn't change
232
- # anything.
233
- if count :
234
- fh .seek (0 )
235
- fh .write (content )
236
- fh .truncate ()
237
- return count
227
+ try :
228
+ with path .open ("r+" ) as fh :
229
+ return _replace_in_file_handle (fh , expr , replacement )
230
+ except UnicodeDecodeError :
231
+ pass # It's a binary file. Try again with a binary regular expression.
232
+ flags = expr .flags & ~ re .UNICODE
233
+ expr = re .compile (expr .pattern .encode (), flags )
234
+ with path .open ("rb+" ) as fh :
235
+ return _replace_in_file_handle (fh , expr , replacement .encode ())
236
+
237
+
238
+ def _replace_in_file_handle (fh , expr , replacement ):
239
+ content = fh .read ()
240
+ content , count = expr .subn (replacement , content )
241
+
242
+ # Don't bother writing the file if we didn't change
243
+ # anything.
244
+ if count :
245
+ fh .seek (0 )
246
+ fh .write (content )
247
+ fh .truncate ()
248
+ return count
238
249
239
250
240
251
def replace (
You can’t perform that action at this time.
0 commit comments