【问题标题】:How do I read only a part of a file in Python?如何在 Python 中只读取文件的一部分?
【发布时间】: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


【解决方案1】:

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

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    相关资源
    最近更新 更多