Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中如何获取if之后的下一行_Python - Fatal编程技术网

在python中如何获取if之后的下一行

在python中如何获取if之后的下一行,python,Python,你好,我有一个这样的文件: A. B. C. D. E. A. D. A. F. S. with open("./f") as f: read_next = False for line in f: if line.strip() == 'A.': read_next = True continue if read_next: read_next = False print line 我想在A之后立即打印这些行 您可以

你好,我有一个这样的文件:

A.
B.
C.
D.
E.
A.
D.
A.
F.
S.
with open("./f") as f:
  read_next = False
  for line in f:
    if line.strip() == 'A.':
      read_next = True
      continue

    if read_next:
      read_next = False
      print line
我想在
A
之后立即打印这些行


您可以这样做:

A.
B.
C.
D.
E.
A.
D.
A.
F.
S.
with open("./f") as f:
  read_next = False
  for line in f:
    if line.strip() == 'A.':
      read_next = True
      continue

    if read_next:
      read_next = False
      print line
其中文件
/f
包含:

A.
B.
C.
D.
E.
A.
D.
A.
F.
S.
这就产生了:

B.

D.

F.
需要将所有数据读入内存的更简单方法如下:

with open("./f") as f:
  lines = f.read().splitlines()
  for i,line in enumerate(lines):
    if line == 'A.' and i < (len(lines)-1):
      print lines[i+1]
打开(“./f”)作为f的
:
lines=f.read().splitlines()
对于i,枚举中的行(行):
如果行==“A.”且i<(len(行)-1):
打印行[i+1]

正则表达式完成任务

import re

your_file = open("your_file", "r")
content = your_file.read()
your_file.close()

# Looks for "A.\n" and grabs the character and period after it.
matches = re.search("A\.\n([A-Z]\.)", content)

打印('B')
不起作用?欢迎使用堆栈溢出。我们不是家庭作业服务机构;请看看为什么这不是一个好问题。如果这实际上是家庭作业,@lxop我想要根据这个文件的b,d,f