SAK SAK - 3 months ago 10
Python Question

how to join incorporate splitted lines with replacing data from a file into the same string

So as most of us are thinking it's a duplicate which is not, so what I'm trying to achieve is let's say there is a Master string like the below and couple of files mentioned in it then we need to open the files and check if there are any other files included in it, if so we need to copy that into the line where we fetched that particular text.

Master String:


Welcome

How are you

file.txt

everything alright

signature.txt

Thanks


file.txt

ABCD
EFGH
tele.txt

tele.txt


IJKL


signature.txt


SAK


Output:

Welcome

How are you

ABCD

EFGH

IJKL

everything alright

SAK

Thanks


for msplitin [stext.split('\n')]:
for num, items in enumerate(stext,1):
if items.strip().startswith("here is") and items.strip().endswith(".txt"):
gmsf = open(os.path.join(os.getcwd()+"\txt", items[8:]), "r")
gmsfstr = gmsf.read()
newline = items.replace(items, gmsfstr)


How to join these replace items in the same string format.

Also, any idea on how to re-iterate the same function until there are no ".txt". So, once the join is done there might be other ".txt" inside a ".txt.

Thanks for your help in advance.

Answer

You can try:

s = """Welcome
How are you
here is file.txt
everything alright
here is signature.txt
Thanks"""

data = s.split("\n")
match = ['.txt']
all_matches = [s for s in data if any(xs in s for xs in match)]

for index, item in enumerate(data):
    if item in all_matches:
        data[index] ="XYZ"

data = "\n".join(data)
print data

Output:

Welcome
How are you
XYZ
everything alright
XYZ
Thanks

Added new requirement:

def file_obj(filename):
        fo = open(filename,"r")
        s = fo.readlines()
        data = s.split("\n")
        match = ['.txt']
        all_matches = [s for s in data if any(xs in s for xs in match)]
        for index, item in enumerate(data):
                if item in all_matches:
                        file_obj(item)
                        data[index] ="XYZ"

        data = "\n".join(data)
        print data
file_obj("first_filename")