Regex 如何在Python中仅读取文件的一部分?

Regex 如何在Python中仅读取文件的一部分?,regex,python-3.x,string,file-io,Regex,Python 3.x,String,File Io,food.txt ~ Oils, Vinegars and Condiments -- Oils: canola oil, extra-virgin olive oil, toasted sesame -- Vinegars: balsamic, distilled white, red wine, rice -- Ketchup -- Mayonnaise -- Dijon mustard -- Soy sauce -- Chili paste -- Hot sauce -- Worces

food.txt


~ Oils, Vinegars and Condiments

-- Oils: canola oil, extra-virgin olive oil, toasted sesame
-- Vinegars: balsamic, distilled white, red wine, rice
-- Ketchup
-- Mayonnaise
-- Dijon mustard
-- Soy sauce
-- Chili paste
-- Hot sauce
-- Worcestershire

====================================
~ Seasonings

-- Kosher salt

-- Black peppercorns

-- Dried herbs and spices: bay leaves, cayenne pepper, crushed red pepper, cumin, ground coriander, oregano, paprika, rosemary, thyme leaves, cinnamon, cloves, allspice, ginger, nutmeg

-- Spice blends: chili powder, curry powder, Italian seasoning

-- Vanilla extract
====================================
~
Canned Goods and Bottled Items

-- Canned beans: black, cannellini, chickpeas, kidney

-- Capers

-- Olives

-- Peanut butter

-- Preserves or jelly

-- Low-sodium stock or broth

-- Canned tomatoes

-- Tomatoes, canned and paste

-- Salsa

-- Tuna fish


====================================
如何实现只读:

~ Oils, Vinegars and Condiments

-- Oils: canola oil, extra-virgin olive oil, toasted sesame
-- Vinegars: balsamic, distilled white, red wine, rice
-- Ketchup
-- Mayonnaise
-- Dijon mustard
-- Soy sauce
-- Chili paste
-- Hot sauce
-- Worcestershire
filereader.py

import re

regex = (r"^(~\WOil.*)$", r"^=*=$")
with open(filename, "r") as file_handler:
        # Print section of file as String
我只是不知道该怎么办。当使用字符串Obj中的find()和File对象中的seek()时,会出现错误和空白


引用:并且不需要为此使用正则表达式。只需阅读,直到找到分段分隔符:

with open('food.txt') as f:
    for line in iter(f.readline, '====================================\n'):
        print(line, end='')
如果要将文本另存为变量:

with open('food.txt') as f:
    text = ''.join(iter(f.readline, '====================================\n'))
要清除末尾多余的空行,请执行以下操作:

text = text.strip()

看起来你只想要第一部分。为什么不在行中插入“===”:break或类似的东西?