0

I am Recently quite new to python and am trying to write a script. What would be the easiest way to search for a string in a file and replace the whole line. I have found that re.sub can achieve this, but nothing is specific enough that I can do it.

For example:

    #configuration file
    Stuff that configures a file

to

    #configuration file
    Port 22

by searching for configures

Also does this command have different functions such as searching for a string in the middle of a line and replacing everything after it.

Irfan
  • 1
  • 1

1 Answers1

1

You can use replace() to replace the port number.

with open('resume.txt', 'r') as file:
    file_data = file.read()
    upd_port = file_data.replace('22', '4832')
with open('resume.txt', 'w') as file:
    file.write(upd_port)
FELASNIPER
  • 327
  • 2
  • 9