0

I opened a file using open() in python, how would I find and replace a line using a string in that file. Something like this: snbsjasbnjsnsn : 200

open("file","a+")
line = file.find("snbsjasbnjsnsn").line
file.replace(line,"snbsjasbnjsnsn : 199")

The closest thing I found was this

  • 2
    It is not possible to replace something in a file, unless it happens to have the same length. The usual way to replace something in a file is to read the source file, replace and write into a temporary file, then use `os.replace` to atomically replace the original file with the temporary file. – Amadan May 06 '21 at 03:16
  • Thanks, I'm going to try that. Do I leave the question open?@Amadan – shayan bahrainy May 06 '21 at 03:19
  • However, if you can use a package, it seems one does actually exist. I have linked a duplicate question with a variety of methods to solve this problem. – Amadan May 06 '21 at 03:26
  • Thanks I got a way to use `os.replace` – shayan bahrainy May 06 '21 at 03:32

0 Answers0