Python Forum

Full Version: update txt file but keep a specific line
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I'd like run "an update a file from a template file" routine.

Setup:
target file (target.txt)
template file (template.txt)

Info:
target file has no value but for one important line ("InstallGUID").
target file can't be deleted, so must be altered.
num of lines in target file can vary from the template file, so longer is very much possible (and NOT what should happen, all info must be deleted BUT the InstallGUID line).

In easy language (how I do things right now using plain windows 10, 2x notepad):
Open target.txt search for line starts with 'keeper', select that line, ctrl+c
Open template.txt search for line starts with 'keeper', select that line, ctrl+v
Ctrl+a and ctrl+c in template.txt
Ctrl+a in ctrl+v in target.txt
close

My attempt & question:
Works but it doesn't rule out any possible cases where target.lines > template.lines. How to prevent that?

template = "template.txt"
target = "target.txt"
with open(target, 'r') as test:
	for t in test:
		if t.startswith("InstallGUID"):
			installguid = t
		
with open(template, 'r') as rf:
    with open(target, 'w+') as wf:        
		for line in rf:
			if line.startswith("InstallGUID"):
				wf.write(installguid)
			else:
				wf.write(line)
I don't understand what can go wrong with your attempt. Can you give a concrete short example?
Hi Gribouillis,

You are probably not wrong, I think I don't fully understand the write command.

I thought that:
if source file has 20 lines
and
target file has 30 lines
only 20 lines were overwritten by the source file.

But I ran a test and that didn't happen. The target file ended with 20 lines.

So I guess I have some catching up to do on that topic.