123

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

Yaman Jain
  • 1,254
  • 11
  • 16
Joey
  • 1,297
  • 2
  • 8
  • 5
  • 9
    Please (as always) follow [general question guidelines](http://tinyurl.com/so-hints), state any special restrictions, show what you've tried so far, and ask about what specifically is confusing you. –  Nov 08 '10 at 21:23
  • 2
    related: [How to search and replace text in a file using Python?](http://stackoverflow.com/q/17140886/4279) – jfs Sep 17 '14 at 07:48

8 Answers8

215
with open("Stud.txt", "rt") as fin:
    with open("out.txt", "wt") as fout:
        for line in fin:
            fout.write(line.replace('A', 'Orange'))
Gareth Davidson
  • 4,857
  • 2
  • 26
  • 45
  • 9
    "t" for text mode is Python 3 only. Also, you provide a context manager for your ouput file, but fail to close your input file, which seems inconsistent. – Steven Rumbalski Nov 08 '10 at 21:50
  • 1
    but you are renaming the file, this way, and worse, you are creating a new one –  Jun 06 '14 at 08:44
  • 1
    @nakkini Removing the old file and renaming the new is the standard way to do that sort of thing, there is no operating system that supports text files as streams of editable lines. Interesting that you'd think of it that way though. – Gareth Davidson Jun 07 '14 at 15:01
101

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.

Nazareno Lorenzo
  • 1,069
  • 2
  • 14
  • 25
Adam Matan
  • 128,757
  • 147
  • 397
  • 562
  • 1
    This solution is better because you do not rename the file unlike in the above answer. –  Jun 06 '14 at 08:43
  • Better is relative. If you do not want to modify the input file, the other answer is better. It depends on the use case. Both are helpful. – László Papp Jun 24 '22 at 11:20
86
#!/usr/bin/python

with open(FileName) as f:
    newText=f.read().replace('A', 'Orange')

with open(FileName, "w") as f:
    f.write(newText)
GramThanos
  • 3,572
  • 1
  • 22
  • 34
Mark Kahn
  • 1,130
  • 10
  • 8
22

Using pathlib (https://docs.python.org/3/library/pathlib.html)

from pathlib import Path
file = Path('Stud.txt')
file.write_text(file.read_text().replace('A', 'Orange'))

If input and output files were different you would use two different variables for read_text and write_text.

If you wanted a change more complex than a single replacement, you would assign the result of read_text to a variable, process it and save the new content to another variable, and then save the new content with write_text.

If your file was large you would prefer an approach that does not read the whole file in memory, but rather process it line by line as show by Gareth Davidson in another answer (https://stackoverflow.com/a/4128192/3981273), which of course requires to use two distinct files for input and output.

Jorge Moraleda
  • 362
  • 3
  • 8
11

Something like

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

<do stuff with the result>
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
  • 1
    OP menioned "any occurences" this means, even when it is a substring - which will not work for your example. – Durdu Jun 18 '19 at 12:47
10
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:
        f.write(line)
Falmarri
  • 47,727
  • 41
  • 151
  • 191
6

If you are on linux and just want to replace the word dog with catyou can do:

text.txt:

Hi, i am a dog and dog's are awesome, i love dogs! dog dog dogs!

Linux Command:

sed -i 's/dog/cat/g' test.txt

Output:

Hi, i am a cat and cat's are awesome, i love cats! cat cat cats!

Original Post: https://askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands

user1767754
  • 23,311
  • 18
  • 141
  • 164
-1

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.

saved_input
for eachLine in input:
    saved_input.append(eachLine)

#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:
    input.write(each)
Ruli
  • 2,592
  • 12
  • 30
  • 40
austinbv
  • 9,297
  • 6
  • 50
  • 82