Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a whole line in a txt file

I'am new to Python 3 and could really use a little help. I have a txt file containing:

InstallPrompt=

DisplayLicense=

FinishMessage=

TargetName=D:\somewhere

FriendlyName=something

I have a python script that in the end, should change just two lines to:

TargetName=D:\new

FriendlyName=Big

Could anyone help me, please? I have tried to search for it, but I didnt find something I could use. The text that should be replaced could have different length.

like image 424
user302935 Avatar asked Mar 26 '10 23:03

user302935


People also ask

How do you edit a line in a text file in Python?

To edit specific line in text file in Python, we can call readlines to read all the lines in the text file. And then we call writelines to write the new content into the same file after updating the file.


2 Answers

import fileinput
for line in fileinput.FileInput("file",inplace=1):
    sline=line.strip().split("=")
    if sline[0].startswith("TargetName"):
        sline[1]="new.txt"
    elif sline[0].startswith("FriendlyName"):
        sline[1]="big"
    line='='.join(sline)    
    print(line)
like image 182
ghostdog74 Avatar answered Sep 23 '22 19:09

ghostdog74


A very simple solution for what you're doing:

#!/usr/bin/python
import re
import sys
for line in open(sys.argv[1],'r').readlines():
  line = re.sub(r'TargetName=.+',r'TargetName=D:\\new', line)
  line = re.sub(r'FriendlyName=.+',r'FriendlyName=big', line)
  print line,

You would invoke this from the command line as ./test.py myfile.txt > output.txt

like image 42
Dan Story Avatar answered Sep 19 '22 19:09

Dan Story