Replace string within file contents

后端 未结 8 1764
不知归路
不知归路 2020-12-01 00:28

How can I open a file, Stud.txt, and then replace any occurences of \"A\" with \"Orange\"?

8条回答
  •  日久生厌
    2020-12-01 01:02

    If you'd like to replace the strings in the same file, you probably have to read its contents into a local variable, close it, and re-open it for writing:

    I am using the with statement in this example, which closes the file after the with block is terminated - either normally when the last command finishes executing, or by an exception.

    def inplace_change(filename, old_string, new_string):
        # Safely read the input filename using 'with'
        with open(filename) as f:
            s = f.read()
            if old_string not in s:
                print('"{old_string}" not found in {filename}.'.format(**locals()))
                return
    
        # Safely write the changed content, if found in the file
        with open(filename, 'w') as f:
            print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
            s = s.replace(old_string, new_string)
            f.write(s)
    

    It is worth mentioning that if the filenames were different, we could have done this more elegantly with a single with statement.

提交回复
热议问题