Replace a string, in-place, in a text file, throughout. Does not return anything, side-effect only. Inputs are: file_path, a string with the path to the ascii file to edit match_str, the substring to be replaced (as many times as it's found) sub_str, the string
(file_path, match_str, sub_str)
| 16 | |
| 17 | |
| 18 | def replace_str_in_file(file_path, match_str, sub_str): |
| 19 | """ |
| 20 | Replace a string, in-place, in a text file, throughout. |
| 21 | Does not return anything, side-effect only. |
| 22 | Inputs are: |
| 23 | file_path, a string with the path to the ascii file to edit |
| 24 | match_str, the substring to be replaced (as many times as it's found) |
| 25 | sub_str, the string to insert in place of match_str |
| 26 | NOTE: not suitable for very large files (it does all in-memory). |
| 27 | """ |
| 28 | with open(file_path, "r") as f: |
| 29 | contents = f.read() |
| 30 | contents = contents.replace(match_str, sub_str) |
| 31 | with open(file_path, "wt") as f: |
| 32 | f.write(contents) |
| 33 | |
| 34 | |
| 35 | def remove_lines_from_file(file_path, match_str, partial=True): |
no test coverage detected