Replace entire line in txt file

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

InstallPrompt= DisplayLicense= FinishMessage= TargetName=D:\somewhere FriendlyName=something 

I have a python script that should only change two lines in the end:

 TargetName=D:\new FriendlyName=Big 

Can someone help me please? I tried to find it, but I did not find what I could use. The text to be replaced may have different lengths.

+4
source share
5 answers

A very simple solution for what you are 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 call it from the command line as ./test.py myfile.txt > output.txt

+2
source
 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) 
+3
source

Writing to a temporary file and renaming is the best way to make sure that you don’t get the damaged file if something goes wrong.

 import os from tempfile import NamedTemporaryFile fname = "lines.txt" with open(fname) as fin, NamedTemporaryFile(dir='.', delete=False) as fout: for line in fin: if line.startswith("TargetName="): line = "TargetName=D:\\new\n" elif line.startswith("FriendlyName"): line = "FriendlyName=Big\n" fout.write(line.encode('utf8')) os.rename(fout.name, fname) 
+1
source

Is this the config file (.ini) that you are trying to parse? The format looks suspiciously similar, except without a title. You can use configparser , although it can add extra space around the = sign (ie, " TargetName=D:\new " versus " TargetName = D:\new "), but if these changes are not important to you, use configparser easier and less error prone than trying to parse it manually each time.

txt (ini) file:

 [section name] FinishMessage= TargetName=D:\something FriendlyName=something 

the code:

 import sys from configparser import SafeConfigParser def main(): cp = SafeConfigParser() cp.optionxform = str # Preserves case sensitivity cp.readfp(open(sys.argv[1], 'r')) section = 'section name' options = {'TargetName': r'D:\new', 'FriendlyName': 'Big'} for option, value in options.items(): cp.set(section, option, value) cp.write(open(sys.argv[1], 'w')) if __name__ == '__main__': main() 

txt (ini) file (after):

 [section name] FinishMessage = TargetName = D:\new FriendlyName = Big 
+1
source

subs_names.py script runs both Python 2.6+ and Python 3.x:

 #!/usr/bin/env python from __future__ import print_function import sys, fileinput # here goes new values substitions = dict(TargetName=r"D:\new", FriendlyName="Big") inplace = '-i' in sys.argv # make substitions inplace if inplace: sys.argv.remove('-i') for line in fileinput.input(inplace=inplace): name, sep, value = line.partition("=") if name in substitions: print(name, sep, substitions[name], sep='') else: print(line, end='') 

Example:

 $ python3.1 subs_names.py input.txt InstallPrompt= DisplayLicense= FinishMessage= TargetName=D:\new FriendlyName=Big 

If you are satisfied with the result, add the -i option to make changes to the location:

 $ python3.1 subs_names.py -i input.txt 
0
source

Source: https://habr.com/ru/post/1305272/


All Articles