python - 使用一个变量读取两个文件?
问题描述
我一直在网上搜索,但找不到任何东西,所以我不确定是否有可能,但是有什么办法可以读取两个文本文件并将它们放入一个变量中,这样我就可以返回存储在该变量中的数据? 到目前为止,我只是为每个文件复制并粘贴了相同的 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
解决方案
您需要 afor
循环浏览文件,因此您不需要手动执行此操作,也使用regex
get 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
推荐阅读
- wordpress - WordPress 管理页面未显示
- javascript - gatsbyjs中如何编译非网页的js文件
- scala - Spark:ColumnType内Array中值的索引
- python - Python 2.7 - Outlook Win32com.client 无法从 .msg 获取发件人的实际电子邮件地址
- typescript - Ionic 4 + Angular 6 PWA 样式不起作用/损坏
- excel - VBA删除excel中的多行
- python - PyMC 采样忽略参数的界限
- c# - 显示所有相同标签的水平范围栏标签
- powerbi - 刷新 PowerBI 以将重命名的表名称从数据源反映到报表
- json - 以 Json 为参数的 JSONObject