Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replace Line in Textfile
#1
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 written the following:

f = open("test.txt", "rt")
data = f.read()
data = data.replace('python', 'Hello')
f.close()
f = open("test.txt", "wt")
f.write(data)
f.close()
which replaces the word 'python' with the word 'hello'. Easy.

But, how do I combine that with an If statement? Let's say the file only contains a single word: python. How do I get the system to check the single line in the file and, if it says 'python' replace it with the word 'hello', if it says anything else, print whatever the file contains?

It feels like it should be really simple, I just can't get there.
Reply
#2
it's better to use a with statement, makes code easier to read, and closes files automatically:
import os
# assure in script directory
os.chdir(os.path.abspath(os.path.dirname(__file__)))

def replace_a_line(original_line, new_line, filein, fileout):    
    with open(filein) as fin, open(fileout, 'w') as fout:
        for line in fin:
            lineout = line
            if line.strip() == original_line:
                lineout = f"{new_line}\n"
            fout.write(lineout)

def testit():
    replace_a_line('line 2', 'line xxx', 'testfilein.txt', 'testfileout.txt')

if __name__ == '__main__':
    testit()
testfilein.txt:
Output:
line 1 line 2 line 3
testfileout.txt
Output:
line 1 line xxx line 3
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  textfile to customtkinter combobox janeik 6 1,652 Aug-31-2023, 02:50 AM
Last Post: deanhystad
  Importing python data to Textfile or CSV yanDvator 0 1,720 Aug-02-2020, 06:58 AM
Last Post: yanDvator
  Replace every 20th space with line feed T_Lafferty 3 2,330 Jul-19-2020, 10:37 PM
Last Post: T_Lafferty
  Regex won't replace character with line break Tomf96 2 2,500 Jan-12-2020, 12:14 PM
Last Post: Tomf96
  How do you replace a word after a match from a list of words in each line of a file? vijju56 1 3,415 Oct-17-2019, 03:04 PM
Last Post: baquerik
  Read each line, replace string and save into a new file igormonteiro 2 3,218 Sep-15-2019, 01:24 PM
Last Post: buran
  Compare input() to textfile Trianne 4 3,464 Sep-29-2018, 02:32 PM
Last Post: gruntfutuk
  Search & Replace - Newlines Added After Replace dj99 3 3,355 Jul-22-2018, 01:42 PM
Last Post: buran
  Help with python code to search string in one file & replace with line in other file mforthman 26 11,682 Dec-19-2017, 07:11 PM
Last Post: Larz60+
  search and replace with line in document chickflick91 2 3,323 Oct-15-2017, 06:33 AM
Last Post: chickflick91

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020