简体   繁体   中英

How do I read only a part of a file in Python?

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


====================================

How do you read only:

~ 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

I just don't know what to do. I get error and blanks when using find() from String Obj and seek() from File object.

References: How do I read a specific line of a .txt file with Python 3? I only want to read one line and save it as a variable and not all the lines. and Reading a file for a certain section in python

You don't need to use a regex for this. Just read until you find the section separator:

with open('food.txt') as f:
    for line in iter(f.readline, '====================================\n'):
        print(line, end='')

If you want to save the text as a variable:

with open('food.txt') as f:
    text = ''.join(iter(f.readline, '====================================\n'))

To get rid of the extra empty line at the end:

text = text.strip()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM