如何加入合并分割线,将文件中的数据替换为相同的字符串

时间:2016-08-23 06:07:42

标签: python python-2.7 python-3.x

因为我们大多数人都认为它不是重复的,所以我想要实现的是让我们说有一个像下面这样的主字符串和提到的几个文件然后我们需要打开文件并检查其中是否包含任何其他文件,如果是这样,我们需要将其复制到我们获取该特定文本的行中。

主字符串:

  

欢迎
  你好吗?   file.txt的
  一切都好了   signature.txt
  谢谢

file.txt的

ABCD
EFGH
tele.txt

tele.txt

  

IJKL

signature.txt

  

SAK

输出:

欢迎
你好吗? ABCD
EFGH
IJKL
一切都好了 SAK
谢谢你

header("Content-Disposition: attachment; filename= 'asd.zip'");
header("Content-Type: application/octet-stream");
header('X-Accel-Redirect: http://subdomain.samedomain.com/upload/files/qwe.zip');
header("X-Accel-Buffering: yes");
header("X-Accel-Limit-Rate: 102400");

如何以相同的字符串格式连接这些替换项目。

此外,任何想法如何重新迭代相同的功能,直到没有" .txt"。因此,一旦完成连接,可能会有其他的" .txt"在" .txt。

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

您可以尝试:

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

答案 1 :(得分:1)

一种递归方法,适用于任何级别的文件名嵌套:

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)

答案 2 :(得分:0)

我们可以创建临时文件对象并将替换的行保留在该临时文件对象中,一旦处理完所有行,我们就可以将新内容替换为原始文件。一旦临时文件从'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()