The shortest way would probably be to use the fileinput module. For example, the following adds line numbers to a file, in-place:

import fileinput

for line in fileinput.input("test.txt", inplace=True):
    print('{} {}'.format(fileinput.filelineno(), line), end='') # for Python 3
    # print "%d: %s" % (fileinput.filelineno(), line), # for Python 2

What happens here is:

  1. The original file is moved to a backup file
  2. The standard output is redirected to the original file within the loop
  3. Thus any print statements write back into the original file

fileinput has more bells and whistles. For example, it can be used to automatically operate on all files in sys.args[1:], without your having to iterate over them explicitly. Starting with Python 3.2 it also provides a convenient context manager for use in a with statement.


While fileinput is great for throwaway scripts, I would be wary of using it in real code because admittedly it's not very readable or familiar. In real (production) code it's worthwhile to spend just a few more lines of code to make the process explicit and thus make the code readable.

There are two options:

  1. The file is not overly large, and you can just read it wholly to memory. Then close the file, reopen it in writing mode and write the modified contents back.
  2. The file is too large to be stored in memory; you can move it over to a temporary file and open that, reading it line by line, writing back into the original file. Note that this requires twice the storage.
Answer from Eli Bendersky on Stack Overflow
Top answer
1 of 13
316

The shortest way would probably be to use the fileinput module. For example, the following adds line numbers to a file, in-place:

import fileinput

for line in fileinput.input("test.txt", inplace=True):
    print('{} {}'.format(fileinput.filelineno(), line), end='') # for Python 3
    # print "%d: %s" % (fileinput.filelineno(), line), # for Python 2

What happens here is:

  1. The original file is moved to a backup file
  2. The standard output is redirected to the original file within the loop
  3. Thus any print statements write back into the original file

fileinput has more bells and whistles. For example, it can be used to automatically operate on all files in sys.args[1:], without your having to iterate over them explicitly. Starting with Python 3.2 it also provides a convenient context manager for use in a with statement.


While fileinput is great for throwaway scripts, I would be wary of using it in real code because admittedly it's not very readable or familiar. In real (production) code it's worthwhile to spend just a few more lines of code to make the process explicit and thus make the code readable.

There are two options:

  1. The file is not overly large, and you can just read it wholly to memory. Then close the file, reopen it in writing mode and write the modified contents back.
  2. The file is too large to be stored in memory; you can move it over to a temporary file and open that, reading it line by line, writing back into the original file. Note that this requires twice the storage.
2 of 13
236

I guess something like this should do it. It basically writes the content to a new file and replaces the old file with the new file:

from tempfile import mkstemp
from shutil import move, copymode
from os import fdopen, remove

def replace(file_path, pattern, subst):
    #Create temp file
    fh, abs_path = mkstemp()
    with fdopen(fh,'w') as new_file:
        with open(file_path) as old_file:
            for line in old_file:
                new_file.write(line.replace(pattern, subst))
    #Copy the file permissions from the old file to the new file
    copymode(file_path, abs_path)
    #Remove original file
    remove(file_path)
    #Move new file
    move(abs_path, file_path)
🌐
Delft Stack
delftstack.com › home › howto › python › python replace line in file
How to Replace a Line in a File in Python | Delft Stack
February 12, 2024 - Using a for loop, we iterate through each line in the lines list, apply the replace() function to substitute hardships with situations, and write the updated line back to the file.
Discussions

Replace text in a file
filename = input('Enter file name: ') old_word = input('Enter a string to be replaced: ') new_word = input('Enter a string to be added: ') with open(filename, 'r') as infile: file = infile.read() file = file.replace(old_word, new_word) with open(filename, 'w') as ofile: ofile.write(file) When you leave the with context, then the file is automatically closed. I renamed the variables so hopefully that makes it easier to see what you were doing wrong. More on reddit.com
🌐 r/pythonhelp
3
2
May 26, 2022
Find and replace text
Hi Guys, I am fairly new to python. I am trying to find and replace texts on one file with the help of another file which has the list of texts to be replaced with. File 1 : Is the actual file which requires the replacement of texts File 2 : Has the list of texts that needs to be replaced File ... More on discuss.python.org
🌐 discuss.python.org
2
0
January 20, 2024
python - Replace string within file contents - Stack Overflow
How can I open a file, Stud.txt, and then replace any occurences of "A" with "Orange"? More on stackoverflow.com
🌐 stackoverflow.com
Replace string in a specific line using python - Stack Overflow
I'm writing a python script to replace strings from a each text file in a directory with a specific extension (.seq). The strings replaced should only be from the second line of each file, and the output is a new subdirectory (call it clean) with the same file names as the original files, but with a *.clean suffix. The output file contains ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Finxter
blog.finxter.com › home › learn python blog › how to search and replace a line in a file in python? 5 simple ways
How to Search and Replace a Line in a File in Python? 5 Simple Ways - Be on the Right Side of Change
August 3, 2022 - To replace a specific line number in a file, loop through each line in the text file and find the line number to be replaced and then replace it with the new string using the replace() method.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-search-and-replace-text-in-a-file-in-python
How to Search and Replace Text in a file in Python - GeeksforGeeks
June 21, 2025 - string : Text you want to replace · Example: Python · import re def replacetext(search_text, replace_text): with open('SampleFile.txt', 'r+') as f: file_data = f.read() file_data = re.sub(search_text, replace_text, file_data) f.seek(0) f.write(file_data) f.truncate() return "Text replaced" print(replacetext("dummy", "replaced")) Output: Text replaced · fileinput is a powerful tool for line-by-line replacement and supports in-place editing with optional backup creation.
🌐
Python Examples
pythonexamples.org › python-replace-string-in-file
Python – Replace String in File with another String
For each line read from the input file, replace the string and write to the output file. Close both the input and output files. Consider that we have a text file with some spelling mistakes. In this example, we replace the string pyton with python in the data.txt file and write the result to out.txt.
🌐
Kite
kite.com › python › answers › how-to-replace-a-string-within-a-file-in-python
Kite is saying farewell - Code Faster with Kite
November 20, 2022 - P.S. Most of our code has been open sourced on Github here. It includes our data-driven Python type inference engine, Python public-package analyzer, desktop software, editor integrations, Github crawler and analyzer, and much more.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python-program-to-replace-specific-line-in-file
Python Program to Replace Specific Line in File - GeeksforGeeks
September 14, 2021 - The splitfields() method is a user-defined method written in Python that splits any kind of data into a list of fields using a delimiter. The delimiter can be specified as an argument to the method, and if no delimiter is specified, the method ...
🌐
Reddit
reddit.com › r/pythonhelp › replace text in a file
r/pythonhelp on Reddit: Replace text in a file
May 26, 2022 -

Homework assignment. I have to open a file from a user input as read only. Close the file. Replace the text from the other user inputs. Open the file to write. Close it again. Then open and print.

file = input('Enter file name:')
old_word = input('Enter a string to be replaced: ')
new_word = input('Enter a string to be added: ')

with open(file, 'r') as infile:
    file = infile.read()
    
infile.close()

with open(file, 'w') as infile:
    file = infile.write()

file = file.replace(old_word, new_word)

I keep getting an "OSError: [Errno 22]" when it tries to open 'file' again. Any help would be appreciated.

🌐
Python.org
discuss.python.org › python help
Find and replace text - Python Help - Discussions on Python.org
January 20, 2024 - Hi Guys, I am fairly new to python. I am trying to find and replace texts on one file with the help of another file which has the list of texts to be replaced with. File 1 : Is the actual file which requires the replace…
🌐
YouTube
youtube.com › watch
Replace A Specific Line In A File | Python Examples - YouTube
How to replace a specific line in a file using Python (i.e. a line at a specific line number). Source code: https://github.com/portfoliocourses/python-exampl...
Published: August 11, 2022
🌐
Linux Hint
linuxhint.com › python-replaces-string-file
Linux Hint – Linux Hint
May 23, 2023 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
Python Forum
python-forum.io › thread-22229.html
Replace Line in Textfile
November 4, 2019 - I have a really simple query, but I can't find an answer to it. I'm new to Python and am learning for a project I'm setting up, but I seem to have fallen at the first hurdle. All I want to do is replace a line in a text file. That's it. So, I've wri...
🌐
O'Reilly
oreilly.com › library › view › python-cookbook › 0596001673 › ch04s04.html
Searching and Replacing Text in a File - Python Cookbook [Book]
July 19, 2002 - String substitution is most simply performed by the replace method of string objects. The work here is to support reading from the specified file (or standard input) and writing to the specified file (or standard output): #!/usr/bin/env python import os, sys nargs = len(sys.argv) if not 3 <= nargs <= 5: print "usage: %s search_text replace_text [infile [outfile]]" % \ os.path.basename(sys.argv[0]) else: stext = sys.argv[1] rtext = sys.argv[2] input = sys.stdin output = sys.stdout if nargs > 3: input = open(sys.argv[3]) if nargs > 4: output = open(sys.argv[4], 'w') for s in input.xreadlines( ): output.write(s.replace(stext, rtext)) output.close( ) input.close( )
Authors: Alex MartelliDavid Ascher
Published: 2002
Pages: 608
Top answer
1 of 5
10

some notes:

  1. string.replace and re.sub are not in-place so you should be assigning the return value back to your variable.
  2. glob.glob is better for finding files in a directory matching a defined pattern...
  3. maybe you should be checking if the directory already exists before creating it (I just assumed this, this could not be your desired behavior)
  4. the with statement takes care of closing the file in a safe way. if you don't want to use it you have to use try finally.
  5. in your example you where forgetting to put the sufix *.clean ;)
  6. you where not actually writing the files, you could do it like i did in my example or use fileinput module (which until today i did not know)

here's my example:

import re
import os
import glob

source_dir=os.getcwd()
target_dir="clean"
source_files = [fname for fname in glob.glob(os.path.join(source_dir,"*.seq"))]

# check if target directory exists... if not, create it.
if not os.path.exists(target_dir):
    os.makedirs(target_dir)

for source_file in source_files:
   target_file = os.path.join(target_dir,os.path.basename(source_file)+".clean")
   with open(source_file,'r') as sfile:
      with open(target_file,'w') as tfile:
         lines = sfile.readlines()
         # do the replacement in the second line.
         # (remember that arrays are zero indexed)
         lines[1]=re.sub("K|Y|W|M|R|S",'N',lines[1])
         tfile.writelines(lines)

print "DONE"

hope it helps.

2 of 5
5

You should replace line.replace('M', 'N') with line=line.replace('M', 'N'). replace returns a copy of the original string with the relevant substrings replaced.

An even better way (IMO) is to use re.

import re

line="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
line=re.sub("K|Y|W|M|R|S",'N',line)
print line 
🌐
GoLinuxCloud
golinuxcloud.com › home › programming › replace string in file using python
Replace String in File Using Python: Same File, New File, fileinput, and Regex
June 23, 2026 - from pathlib import Path source = Path("a.txt") target = Path("b.txt") with source.open(encoding="utf-8") as src, target.open("w", encoding="utf-8") as dst: for line in src: dst.write(line.replace("input", "output")) ... After the script runs, b.txt contains output instead of input. See Python write to file for more file-writing patterns. For small files, read the entire content, replace the string, and overwrite the file.
Top answer
1 of 6
4

I realized that I was wrong by just an indentation. In the code piece 1 mentioned in the question, if I am bringing the 'print line,' from the scope of if i.e. if i outdent it, then this is solved...

As this line was inside the scope of if, hence, only this new_text was being written to the file, and other lines were not being written, and hence the file was left with only the new_text. So, the code piece should be as follow :-

text = "mov9 = "   # if any line contains this text, I want to modify the whole line.
new_text = "mov9 = Alice in Wonderland"
x = fileinput.input(files="C:\Users\Admin\Desktop\DeletedMovies.txt", inplace=1)
for line in x:
    if text in line:
        line = new_text
    print line,
x.close()

Also, the second solution given by Rolf of Saxony & the first solution by Padraic Cunningham is somehow similar.

2 of 6
1

You empty you file because you only write when you find a match, you need to always write the lines:

import sys

text = "mov9 = "   # if any line contains this text, I want to modify the whole line.
new_text = "mov9 = Alice in Wonderland\n"

x = fileinput.input(files="C:\Users\Admin\Desktop\DeletedMovies.txt", inplace=1)
for line in x:
    if text in line:
        line = new_text
    sys.stdout.write(line)

If you find a match the line will be set to new_text, so either sys.stdout.write(line) will write the original line or new_text. Also if you actually want to find lines starting with text use if line.startswith(text):

You could also write to a tempfile and replace the original:

from shutil import move
from tempfile import NamedTemporaryFile

text = "mov9 = "   # if any line contains this text, I want to modify the whole line.
new_text = "mov9 = Alice in Wonderland\n"

with open("C:\Users\Admin\Desktop\DeletedMovies.txt") as f, NamedTemporaryFile("w", dir=".", delete=False) as tmp:
    for line in f:
        if text in line:
            line = new_text
        tmp.write(line)


move(tmp.name, "C:\Users\Admin\Desktop\DeletedMovies.txt")
🌐
HCL GUVI
studytonight.com › python-howtos › search-and-replace-a-line-in-a-file-in-python
HCL GUVI | Learn to code in your native language
February 23, 2021 - Supports JavaScript, Python, Ruby, and 20+ programming languages.Explore IDE