Python 如何通过将文件中的数据替换为同一字符串来合并拆分的行

Python 如何通过将文件中的数据替换为同一字符串来合并拆分的行,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,因为我们大多数人都认为它是一个重复的,而不是,所以我试图实现的是,假设有一个主字符串,如下面所示,以及其中提到的几个文件,那么我们需要打开这些文件,检查其中是否包含任何其他文件,如果是这样,我们需要将其复制到获取特定文本的行中 主字符串: 欢迎 你好吗 file.txt 一切正常 signature.txt 谢谢 file.txt ABCDEFGHtele.txt tele.txt IJKL signature.txt 萨克 输出: Welcome How are you XYZ everyth

因为我们大多数人都认为它是一个重复的,而不是,所以我试图实现的是,假设有一个主字符串,如下面所示,以及其中提到的几个文件,那么我们需要打开这些文件,检查其中是否包含任何其他文件,如果是这样,我们需要将其复制到获取特定文本的行中

主字符串:

欢迎
你好吗
file.txt
一切正常
signature.txt
谢谢

file.txt

ABCD
EFGH
tele.txt

tele.txt

IJKL

signature.txt

萨克

输出:

Welcome
How are you
XYZ
everything alright
XYZ
Thanks
欢迎
你好吗
ABCD
EFGH
IJKL
一切正常
萨克
谢谢

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)
如何以相同的字符串格式连接这些替换项

还有,关于如何重新迭代相同的函数直到没有“.txt”的想法。因此,一旦连接完成,.txt中可能还有其他“.txt”

提前感谢您的帮助。

您可以尝试:

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
输出:

Welcome
How are you
XYZ
everything alright
XYZ
Thanks
新增要求:

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

我们可以创建临时文件对象,并将替换的行保留在该临时文件对象中,一旦所有行都处理完毕,我们就可以将其替换为原始文件的新内容。该临时文件从“with”语句中出来后将自动删除

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

使用任何级别的文件名嵌套的递归方法:

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)

添加..我用XYZ替换了这两个.txt文件..您可以随意替换..我这样做是因为它将处理最后的数据量..无需替换每个字符串..我认为,要求是打开文件-搜索字符串-如果匹配,然后替换。SAK发布的演示代码包含诸如检查文件是否存在、读取文件内容等操作tsetc@HarshaBiyani谢谢Harsha的帮助。@dinespundkar-我更改了代码,它指向“打开以读取文件”。谢谢你的帮助guys@HarshaBiyani还有,你知道如何重新迭代同一个函数直到没有“.txt”吗?因此,一旦连接完成,在.txt.希望我没有混淆。请检查我的答案。可能重复的请不要不断更改您的问题。@SAK我的荣幸:)我认为您检查了错误的答案tho:)我发现了另一个问题,因此当有两个级别的文件,即file-file-file时,会出现一个错误“无法连接'str'和'NoneType'对象”一秒钟,让我试试它修复了一些行分隔符问题,测试了它到文件,所以应该适合任何级别。现在试试,让我看看know@criagBurgler还不走运,这里是错误代码-m.txt D:/k/m.txt[Errno 22]无效模式('rb')或文件名:u'D:/k/m.txt\r\n'无法连接'str'和'NoneType'对象回溯(最后一次调用):文件“D:\Installation\Python27\Lib\site packages\gevent\greenlet.py”,第522行,在run result=self.\u run(*self.args,**self.kwargs)文件“D:\k\t.py”第72行,在start result=self.do\as文件“D:\k\core\tasks.py”第159行,在do\u work replacemented='\n.连接(行)类型错误:序列项31:应为字符串或Unicode,未找到非类型