0

My file, with the following content:

item1: bar
item2: foo

The code:

with open(filename, 'r') as file_content:
    # perform a logic which modifies file content,
    # for instance replaces every occurence of bar with baz
    yaml_content = yaml.safe_load(file_content)  

Is there any way to modify the stream (file_content) and replace lines on the fly?

Łukasz
  • 1,980
  • 6
  • 32
  • 52
  • Yes, and it's been deeply discussed in many iterations: [here](https://stackoverflow.com/questions/4710067/) and most recently [here](https://stackoverflow.com/questions/58070732/). – Torxed Oct 02 '19 at 11:17
  • Possible duplicate of [using Python for deleting a specific line in a file](https://stackoverflow.com/questions/4710067/using-python-for-deleting-a-specific-line-in-a-file). In short, if you want to replace the line with a line matching the length of your old line. You can do `fh.seek(fh.tell() - len(line))` and just do `fh.write(new_line)` on a `open(filename, 'w+')` handle. – Torxed Oct 02 '19 at 11:17

0 Answers0