【问题标题】:python search a string in a text file and copy a blockpython在文本文件中搜索字符串并复制一个块
【发布时间】:2014-10-21 00:27:07
【问题描述】:

我有这个文本文件名.txt

Daniel
Sam
Sameer
Code
Print
Alpha
Bravo
Charlie

我想在其中搜索字符串“Alpha”并复制“alpha”行和前 100 行,然后将其“追加”到文件 result.txt

 with open(names.txt) as g:
    lines = (g.readlines())
    for line in lines:
        if "{0}".format("Alpha") in line:
          ????????????

我写了这段代码,在这里停了下来,任何人都可以帮忙吗?

【问题讨论】:

  • 您是否遇到特定错误?还是您只是在寻求一般的解决方案
  • @Parker 我不知道接下来要做什么,我是 python 新手,我真的不知道接下来要写什么

标签: python file search text copy


【解决方案1】:

可能最简单的方法是维护您已阅读的最后 100 行的列表,然后如果当前行是 'Alpha',则将它们输出到您的 result.txt 文件:

limit = 100
prev_items = []

# Open file and iterate over lines.
with open('names.txt') as f:
    for line in f:
        # Add the current line to the list.
        prev_items.append(line)
        # Reduce the list to its newest elements.
        prev_items = prev_items[-limit:]

        # If the current line is 'Alpha', we don't need to read any more.
        if line == 'Alpha':
           break

# Append prev_items to the results file.
with open('results.txt', 'a') as f:
    f.write('\n'.join(prev_items))

或者,如果您愿意使用list 以外的集合,请使用deque

from collections import deque

limit = 100
prev_items = deque(maxlen=limit)

# Open file and iterate over lines.
with open('names.txt') as f:
    for line in f:
        # Add the line to the deque.
        prev_items.append(line)

        # If the current line is 'Alpha', we don't need to read any more.
        if line == 'Alpha':
           break

# Append prev_items to the results file.
with open('results.txt', 'a') as f:
    f.write('\n'.join(prev_items))

【讨论】:

  • 谢谢,您的代码运行良好。还有一件事可以告诉我在代码中需要更改什么以将 100 更改为此代码中的变量吗?
  • @Mohammed:我添加了一个 limit 变量来满足您的需求 - 只需进行相应调整即可。 (我还将prev100 更改为prev_items,因为它可能不再有100 个项目了)。
【解决方案2】:

您需要一个计数器来告诉您哪一行包含Alpha,这样您就可以返回并获取您需要的前 100 行。

【讨论】:

    猜你喜欢
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多