【问题标题】:Having next items in a list while we run a for loop在我们运行 for 循环时将下一项放在列表中
【发布时间】:2021-07-16 05:46:56
【问题描述】:

我是 python 的初学者,我正在编写一个代码,我试图检查我是否找到了一个特定的项目,我可以在之前检查一些项目,是否可以打印当前值。 我写了这段代码,但我无法解决问题:

import re

file1 = open('A.txt', 'r')
file2 = open('B.txt', 'w')
line = file1.readlines()
for index, line in enumerate(file1):
     match = re.search(r'R', line)
     if match:
            for a in range(index, index+2):
                 same = re.search(r'T', line.next())
                 if same:
                        file2.writelines(line)


file2.close()
file1.close()

【问题讨论】:

  • 有什么问题?
  • 正如卡米洛所说,不清楚你想要什么。看来您可能会要求在迭代之前比较以前的检查或检查项目?如果您澄清您想要什么,我们可以提供更好的帮助,也许可以展示您想要的输出并告诉我们您当前遇到的问题。
  • 我正在寻找一个指定的字符。然后如果第二个下一行是另一个指定的字符,则打印你找到的那个。

标签: python file for-loop enumerate file-read


【解决方案1】:

你的问题不是很清楚,但我怀疑你正在尝试做这样的事情:

如果其中包含 R 字符,则您要确保 line1 来自精细 A.txt 进入文件 B.txt,并且其后跟一行包含 T 字符。这是该问题的解决方案。

import re

file1 = open('A.txt', 'r')
file2 = open('B.txt', 'w')
last_line = file1.readline()
while (current_line := file1.readline()):
    match_last = re.search(r'R', last_line)
    match_current = re.search(r'T', current_line)
    
    if match_last and match_current:
        file2.writelines(last_line)
    last_line = current_line

file2.close()
file1.close()

【讨论】:

  • 没错!我想检查它是否有 R 字符然后例如在下一行的第二行中如果我有 T 然后打印这个 R。基本上,我想访问之前或之后的任何元素。
  • 实际上它起作用了。但是如果我想检查下第二行呢?
  • 您可以将文件转换为行列表。 lines = open('A.txt', 'r').readlines()。然后访问lines[i+1] 获取下一行。
  • 你能写吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-09
  • 1970-01-01
  • 2018-01-17
  • 1970-01-01
  • 2014-03-23
  • 1970-01-01
  • 2020-10-14
相关资源
最近更新 更多