Search
 
SCRIPT & CODE EXAMPLE
 

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.
Comment

PREVIOUS NEXT
Code Example
Python :: get dict values in list python 
Python :: rps python 
Python :: python terminal game 
Python :: add to a list python 
Python :: python remove empty values from list 
Python :: python hasattribute 
Python :: python datetime get date one week from today 
Python :: how to make a python file that prints out a random element from a list 
Python :: django request user 
Python :: install python in dockerfile 
Python :: remove prefix from string python 
Python :: python random walk 
Python :: python int16 
Python :: superscript python 
Python :: mse python 
Python :: print for loop in same line python 
Python :: creating an entry widget for input in tkinter 
Python :: read and write to file python 
Python :: save object pickle python 
Python :: fibonacci series using dynamic programmig approach 
Python :: python private method 
Python :: how to stop all pygame mixer sound 
Python :: AttributeError: ‘numpy.ndarray’ object has no attribute ‘append’ 
Python :: count specific instances in a columb in pandas 
Python :: mulitplication symbo for unpacking in python 
Python :: django queryset count 
Python :: python create temp file 
Python :: how to add char to string python 
Python :: django templates 
Python :: how to convert pandas series to 2d numpy array 
ADD CONTENT
Topic
Content
Source link
Name
7+5 =