【发布时间】:2020-02-26 00:33:53
【问题描述】:
食物.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
我只是不知道该怎么办。使用 String Obj 中的 find() 和 File 对象中的 seek() 时出现错误和空白。
参考: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. 和 Reading a file for a certain section in python
【问题讨论】:
-
您似乎只想要第一部分。为什么不只是
if "======" in line: break或类似的东西?
标签: regex python-3.x string file-io