Fred Bongers Fred Bongers - 7 months ago 27
Python Question

Python replace value in text file

I'm trying to replace a value in a specific line in a text file.

My text file contains count of the searchterm,searchterm & date and time

text file:

MemTotal,5,2016-07-30 12:02:33,781
model name,3,2016-07-30 13:37:59,074
model,3,2016-07-30 15:39:59,075

How can i replace for example the count of the searchterm for line 2 (3,model name,2016-07-30 13:37:59,074)?

This is what i have already:

f = open('file.log','r')
filedata =

newdata = filedata.replace("2","3")

f = open('file.log','w')

It replace all values 2.


You have to change three things in your code to get the job done:

  1. Read the file using readlines.

    filedata = f.readlines()
  2. Modify the line you want to change (keep in mind that Python indices start at 0 and don't forget to add a newline character \n at the end of the string):

    filedata[1] = 'new count,new search term,new date and time\n'
  3. Save the file using a for loop:

    for line in filedata:

Here is the full code (notice I used the with context manager to open/close the file):

with open('file.log', 'r') as f:
    filedata = f.readlines()

filedata[1] = 'new count,new search term,new date and time\n'

with open('file.log', 'w') as f:
    for line in filedata: