Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

how to replace a word in text file using python

# How to replace a word in a text file

filename = "sample1.txt"
# SAMPLE1.TXT
# Hello World!
# I am a human.

with open(filename, 'r+') as f:
    text = f.read()
    text = re.sub('human', 'cat', text)
    f.seek(0)
    f.write(text)
    f.truncate()

# SAMPLE1.TXT
# Hello World!
# I am a cat.
 
PREVIOUS NEXT
Tagged: #replace #word #text #file #python
ADD COMMENT
Topic
Name
6+7 =