【问题标题】:How do you start and end reading a file at a specific string in python?如何在 python 中以特定字符串开始和结束读取文件?
【发布时间】:2019-11-30 06:11:41
【问题描述】:

如何开始和结束读取特定字符串的文件?

例如:

start file
some data
start point
some data
end point
some data
end file

我目前为止:

filename = 'name of file'
with open(filename) as f:
    for line in iter(lambda: f.readline().rstrip(), 'end point'):
        print(line)

【问题讨论】:

  • 示例是您输入文件的内容吗?预期的输出是什么?

标签: python python-2.7 text file-io


【解决方案1】:

这实际上取决于您是读取 n 行,还是读取所有行,直到遇到包含子字符串的特定行。

三个例子:

# Ready file until 'end point' is encountered in a line
with open('sample.txt') as f:
  for line in f:
    # ... do things with the line
    print(line)
    if 'end point' in line:
      print('---')
      break

# Read the first 5 lines
with open('sample.txt') as f:
  lines = [next(f) for x in range(5)]
  print(lines)

# Less performant, read all lines and then slice
with open('sample.txt') as f:
  all_lines = f.readlines()
  print(lines[:5])

【讨论】:

  • 我需要从某个字符串开始,到另一个字符串结束的代码。
猜你喜欢
  • 1970-01-01
  • 2011-04-12
  • 2013-05-18
  • 2017-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多