Replacing Text in a File with Python

How to search and replace text in a file?

fileinput already supports inplace editing. It redirects stdout to the file in this case:

#!/usr/bin/env python3
import fileinput

with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
for line in file:
print(line.replace(text_to_search, replacement_text), end='')

replacing text in a file with Python

This should do it

replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}

with open('path/to/input/file') as infile, open('path/to/output/file', 'w') as outfile:
for line in infile:
for src, target in replacements.items():
line = line.replace(src, target)
outfile.write(line)

EDIT: To address Eildosa's comment, if you wanted to do this without writing to another file, then you'll end up having to read your entire source file into memory:

lines = []
with open('path/to/input/file') as infile:
for line in infile:
for src, target in replacements.items():
line = line.replace(src, target)
lines.append(line)
with open('path/to/input/file', 'w') as outfile:
for line in lines:
outfile.write(line)

Edit: If you are using Python 2.x, use replacements.iteritems() instead of replacements.items()

Replace text in file to new file in for loop with open

I am making some presumptions about the nature of the problem you are attempting to solve, so correct me if I get something wrong.

Presuming you want to replace all instances of "DDD, " (note the extra space) with nothing,

you may want to search for slightly modified strings by adding the extra space... more about this later.

In the snippet below, I added some comments inline to either confirm my understanding OR to clarify what might be awry. A recommendation follows at the end.

weekday = ('Mon,', 'Tue,', 'Wed,', 'Thu,', 'Fri,', 'Sat,', 'Sun,')   

with open(inf, "r") as infile:
with open(outf, "w") as outfile:

# If you intend to call the .write() method, it will need an argument
# so that the function knows what to write.
# At this point, we don't seem to have anything to write, yet.
# I am presuming this next line is out of place.
oline = outfile.write()

for fline in infile:

# weekday is a tuple. It has strings in it, but it is a tuple.
# As such the text in fline will never start with it.
# I feel like you want to cycle through each weekday in weekdays
# and if you find that weekday, you simply want to replace that
# snippet of text, if it is found.
# We will need a different approach, more on this later.

if fline.startswith(weekday):

# It should be noted that .replace() does not do an "in place"
# replacement. If we want to save the results of the replacement,
# we need to set a variable to point at the result.
# Options include either of the following:
# fline = fline.replace("Mon,", " ") if you just want the new data
# newline = fline.replace("Mon,", " ") if you want to keep fline
# untouched for later reference
fline.replace("Mon,", " ")
fline.replace('Tue,', " ")
fline.replace('Wed,', " ")
fline.replace('Thu,', " ")
fline.replace('Fri,', " ")
fline.replace('Sat,', " ")
fline.replace('Sun,', " ")
print(type(fline),fline)

We might rewrite the code in this way.

Again, presuming I understand your end goal:

inf = "/Users/dusti/Documents/datetime25.txt"  
outf = "/Users/dusti/Documents/datetime30.txt"

# We could add a blank space after each string in weekdays AND
# give it the variable name weekdays to better reflect that it is
# a sequence of individual weekdays.

weekdays = ('Mon, ', 'Tue, ', 'Wed, ', 'Thu, ', 'Fri, ', 'Sat, ', 'Sun, ')

with open(inf, "r") as infile:
with open(outf, "w") as outfile:
for fline in infile:

# We could parse each weekday in weekdays
for weekday in weekdays:

# For each weekday in weekdays, we could then
# do a replacement of that weekday, if it exists
# I am presuming that we don't want extraneous blank spaces
# To prevent "Mon, 11 May 2026 05:41:27" from becoming:
# " 11 May 2026 05:41:27"
#
# We use our tuple ("Mon, ", "Tue, "...) with the slightly
# enhanced "space-included" strings AND then we replace the
# term with an empty string will ensure that the value comes out
# as this: "11 May 2026 05:41:27" with no extraneous spaces.

fline = fline.replace(weekday, "") # NOTE the empty string (`""`)
# as a replacement value

# NOTE: this line is outdented from the for loop, cause
# we only want to write to the outfile when we have
# finished checking against each weekday in weekdays and have a
# final result to write.
outfile.write(fline)

Python: Replace last line in text file

file = open('example.txt','r')
lines = file.readlines()[:-1]
lines.append("YOUR NEW LINE")
file.close()
file = open('example.txt','w')
file.writelines(lines)

It cannot be more simpler than replacing one by one all the lines. Here's my answer that has just worked for me.

Replace text in a file between two strings from another text file using python

Read the contents of your file into a string.

with open('your_file', 'r') as f:
contents = f.read()

Get the text between the two occurrences.

starting_text = 'whatever your first bound is'
ending_text = 'whatever your second bound is'
to_replace = contents[contents.find(starting_text)+len(starting_text):contents.rfind(ending_text)]

Then replace it.

contents = contents.replace(to_replace, 'whatever you want to replace it with')

And then you can rewrite it back into a file.

You could use the same approach to find the text that you're going to replace it with if it's in another file.

(This isn't compiled by the way, so it may not be entirely correct)



Related Topics



Leave a reply



Submit