IAmHomes
IAmHomes

Reputation: 523

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.

Upvotes: 1

Views: 168

Answers (3)

Craig Burgler
Craig Burgler

Reputation: 1779

A recursive approach that works with any level of file name nesting:

from os import linesep

def get_text_from_file(file_path):
    with open(file_path) as f:
        text = f.read()
        return SAK_replace(text)

def SAK_replace(s):
    lines = s.splitlines()
    for index, l in enumerate(lines):
        if l.endswith('.txt'):
            lines[index] = get_text_from_file(l)
    return linesep.join(lines)

Upvotes: 1

Sathish
Sathish

Reputation: 51

We can create temporary file object and keep the replaced line in that temporary file object and once everything line is processed then we can replace with the new content to original file. This temporary file will be deleted automatically once its come out from the 'with' statement.

import tempfile
import re

file_pattern = re.compile(ur'(((\w+)\.txt))')
original_content_file_name = 'sample.txt'
"""
sample.txt should have this content.

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


def replace_file_content():
    """
    replace the file content using temporary file object.
    """

    def read_content(file_name):
        # matched file name is read and returned back for replacing.
        content = ""
        with open(file_name) as fileObj:
            content = fileObj.read()
        return content

    # read the file and keep the replaced text in temporary file object(tempfile object will be deleted automatically).
    with open(original_content_file_name, 'r') as file_obj, tempfile.NamedTemporaryFile() as tmp_file:
        for line in file_obj.readlines():
            if line.strip().startswith("here is") and line.strip().endswith(".txt"):
                file_path = re.search(file_pattern, line).group()

                line = read_content(file_path) + '\n'
            tmp_file.write(line)
        tmp_file.seek(0)
        # assign the replaced value to this variable
        replaced_file_str = tmp_file.read()

    # replace with new content to the original file
    with open(original_content_file_name, 'w+') as file_obj:
        file_obj.write(replaced_file_str)

replace_file_content()

Upvotes: 0

Harsha Biyani
Harsha Biyani

Reputation: 7268

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") 

Upvotes: 1

Related Questions