Replace string within file contents

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


with open("Stud.txt", "rt") as fin:
    with open("out.txt", "wt") as fout:
        for line in fin:
            fout.write(line.replace('A', 'Orange'))

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 =
        if old_string not in s:
            print '"{old_string}" not found in {filename}.'.format(**locals())

    # 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)

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

Something like

file = open('Stud.txt')
contents =
replaced_contents = contents.replace('A', 'Orange')

<do stuff with the result>

with open('Stud.txt','r') as f:
    newlines = []
    for line in f.readlines():
        newlines.append(line.replace('A', 'Orange'))
with open('Stud.txt', 'w') as f:
    for line in newlines:


  with open(FileName) as f:'A', 'Orange')

  with open(FileName, "w") as f:

easiest way is to do it with regular expressions, assuming that you want to iterate over each line in the file (where 'A' would be stored) you do...

import re

input = file('C:\full_path\Stud.txt), 'r')
#when you try and write to a file with write permissions, it clears the file and writes only #what you tell it to the file.  So we have to save the file first.

for eachLine in input:

#now we change entries with 'A' to 'Orange'
for i in range(0, len(old):
    search = re.sub('A', 'Orange', saved_input[i])
    if search is not None:
        saved_input[i] = search
#now we open the file in write mode (clearing it) and writing saved_input back to it
input = file('C:\full_path\Stud.txt), 'w')
for each in saved_input:


 ? Replace string within file contents
 ? Replace string within file contents
 ? Replace string within file contents
 ? Backporting Python 3 open(encoding="utf-8") to Python 2
 ? Backporting Python 3 open(encoding="utf-8") to Python 2
 ? Open files in 'rt' and 'wt' modes
 ? While reading file on Python, I faced the error that said UnicodeDecodeError. What can I do to resolve this error?
 ? TypeError: must be unicode, not str in NLTK
 ? Python encoding issue (possibly from windows to linux issue)
 ? TypeError: file() takes at most 3 arguments (4 given)