如何在python中从特定行读取到特定行

2024-06-02 06:14:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件,我想读它的特定部分。这是文件。你知道吗

。。。。。 ..... 管理服务器界面开始 ... .... .... .... .... 管理服务器接口结束 .... .... 你知道吗

我想读取'管理服务器接口开始'到'管理服务器接口结束'之间的部分文件。我在perl中找到了一种方法,但在python中找不到。你知道吗

在perl中

while (<INP>)
{
  print $_ if(/^AdminServer interface definitions begins/ .. /^AdminServer interface definitions ends/);
}

有人能帮忙吗。你知道吗


Tags: 文件方法服务器界面ifinterfaceperlprint
2条回答

如果文件不是很大,并且不关心内存消耗,可以编写以下简单的解决方案:

from os.path import isfile
def collect_admin_server_interface_info(filename):
    """ Collects admin server interface information from specified file. """
    if isfile(filename):
        contents = ''
        with open(filename, 'r') as f:
            contents = file.read()
        beg_str = 'Admin server interface begins'
        end_str = 'Admin server interface ends'
        beg_index = contents.find(beg_str + len(beg_str))
        end_index = contents.find(end_str)
        if beg_index == -1 or end_index == -1:
             raise("Admin server interface not found.")
        return contents[beg_index : end_index]
    else:
        raise("File doesn't exist.")

此方法将尝试返回包含管理员服务器接口信息的单个字符串。你知道吗

您可以逐行读取文件并收集标记之间的内容。你知道吗

def dispatch(inputfile):
    # if the separator lines must be included, set to True
    need_separator = True
    new = False
    rec = []
    with open(inputfile) as f:
        for line in f:
            if "Admin server interface begins" in line:
                new = True
                if need_separator:
                    rec = [line]
                else:
                    rec = []
            elif "Admin server interface ends" in line:
                if need_separator:
                    rec.append(line)
                new = False
                # if you do not need to process further, uncomment the following line
                #return ''.join(rec)
            elif new:
                rec.append(line)
    return ''.join(rec)

即使输入文件不包含结束分隔符(Admin server interface ends),上述代码也将成功返回数据。如果要捕获这样的文件,可以使用条件修改最后的return

if new:
    # handle the case where there is no end separator
    print("Error in input file: no ending separator")
    return ''
else:
    return ''.join(rec)

相关问题 更多 >