Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
850 views
in Technique[技术] by (71.8m points)

variables - How can I use python to insert text from one file to another in various lines?

I am totally new to python, and I have the following question. I have searched quite a bit and while I can find similar questions with answers, I can't find one that addresses the variable nature of mine. So here goes: I have a file that in several places (hundreds) has a line that reads <text = " "> I want to replace each of these lines with lines from a different file in sequential order. Let's say that file reads like this: "abcdefg", "hijklmn" and so on. I want the first instance of <text = " "> to be replaced by "abcdefg", the second by "hijklmn" and so forth. Thank you

question from:https://stackoverflow.com/questions/65852526/how-can-i-use-python-to-insert-text-from-one-file-to-another-in-various-lines

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You didn't specified if the result must be in another file, but I assumed so.

Assuming that foo.txt is the file containing the patter to match (that is <text = " ">), and replacements.txt contains the replacements to put, line by line, this is how to do this task.

import re

with open('foo.txt') as f:
    lines = [line.strip() for line in f.readlines()]

with open('replacements.txt') as f:
    replacements = [line.strip() for line in f.readlines()]

First we read the contents of the files (stripping every line from whitespaces and endline character).

j = 0
for i, line in enumerate(lines):
    result = re.match('<text = " ">', line)
    if result and j < len(replacements):
        lines[i] = replacements[j]
        j += 1

Then we setup a counter for the replacements array, and for every line we search the string to replace.

If it's found and we have replacements to put, we proceed to change that line with the j-th element.

lines = [line + '
' for line in lines]

with open('foo_modified.txt', 'w') as f:
    f.writelines(lines)

Then we join together the modified lines (adding manually the endline character, stripped before), and we write it out in another file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...