首页 > 解决方案 > 使用一个变量读取两个文件?

问题描述

我一直在网上搜索,但找不到任何东西,所以我不确定是否有可能,但是有什么办法可以读取两个文本文件并将它们放入一个变量中,这样我就可以返回存储在该变量中的数据? 到目前为止,我只是为每个文件复制并粘贴了相同的 for 循环,如下所示:

import re


def read_files():
    with open('sample_data_01.txt') as f1, open('sample_data_02.txt') as f2:
        for line in f1:
            pattern = '^en.v\s(\w+)(\D+)(\d+)'
            match = re.findall(pattern, line)
            print(match)
            for line in f2:
                pattern = '^en.v\s(\w+)(\D+)(\d+)'
                match = re.findall(pattern, line)
                print(match)
        return

标签: python

解决方案


您需要 afor循环浏览文件,因此您不需要手动执行此操作,也使用regexget usedr在字符串模式前面添加时,这样您就不会转义不需要的字符,例如:

import re


def read_files():
    matches = []
    for file_path in ('sample_data_01.txt', 'sample_data_02.txt'):
        with open(file_path) as file:
            for line in file.readlines():
                pattern = r'^en.v\s(\w+)(\D+)(\d+)'
                match = re.findall(pattern, line)
                print(match)
                matches.extend(match)
    return matches

推荐阅读