在第n行后打印

时间:2017-08-02 10:38:29

标签: python iterable

我正在尝试在文件中的特定行之后打印第n行:

import glob
import numpy as np
import matplotlib.pyplot as plt
import math

velerror = []
divergence = []
mesh = []
timestep = []
totaltime = []

for files in glob.glob('*.out'):
    f = open(files, 'r')
    for line in f:
        if "Maximum Velocity Error:" in line:
            velerror.append(float(line[32:40]))
        if "Grid Dimensions, Mesh" in line:
            mesh.append(int(line[27]))
        if "Time Step  " in line:
            timestep.append(int(line[17:27].strip()))
        if "Total time:" in line:
            totaltime.append(float(line[47:57].strip()))
            #Print nth line after line


totaltime = totaltime[0::9]

print(velerror)
print(mesh)
print(timestep)
print(totaltime)

是否有像next()这样的函数进入下一行?

6 个答案:

答案 0 :(得分:1)

(请参阅不包含readlines的版本的编辑,live demo

  

在文件中的特定行之后打印第n行

该文件适合内存使用readlines和切片:

def print_after(source, specific_line_number, skip_lines):
    for line in source[specific_line_number::skip_lines]:
        print(line)

lines = [f'line {i:2}' for i in range(30)] # readlines here
print_after(lines, 7, 2)

在您的代码中:

import glob
import numpy as np
import matplotlib.pyplot as plt
import math

velerror = []
divergence = []
mesh = []
timestep = []
totaltime = []

for files in glob.glob('*.out'):
    f = open(files, 'r')
    for line in f:
        if "Maximum Velocity Error:" in line:
            velerror.append(float(line[32:40]))
        if "Grid Dimensions, Mesh" in line:
            mesh.append(int(line[27]))
        if "Time Step  " in line:
            timestep.append(int(line[17:27].strip()))
        if "Total time:" in line:
            totaltime.append(float(line[47:57].strip()))
            for line in islice
            break  # Stop consuming lines (?)


totaltime = totaltime[0::9]

print(velerror)
print(mesh)
print(timestep)
print(totaltime)

编辑:使用islice作为rassahah建议可以帮助你节省一些内存:

from itertools import islice

import glob
import numpy as np
import matplotlib.pyplot as plt
import math

velerror = []
divergence = []
mesh = []
timestep = []
totaltime = []

for files in glob.glob('*.out'):
    f = open(files, 'r')
    for line in f:
        if "Maximum Velocity Error:" in line:
            velerror.append(float(line[32:40]))
        if "Grid Dimensions, Mesh" in line:
            mesh.append(int(line[27]))
        if "Time Step  " in line:
            timestep.append(int(line[17:27].strip()))
        if "Total time:" in line:
            totaltime.append(float(line[47:57].strip()))
            break
    skip_lines = 2
    offset = skip_lines-1
    for line in islice(f, offset, None, skip_lines):
        print(line)


totaltime = totaltime[0::9]

print(velerror)
print(mesh)
print(timestep)
print(totaltime)

答案 1 :(得分:0)

使用readlines()

i = 0;
lines = f.readlines()
while 1:
    line = lines[i]
    if not line:
        break
    if "Maximum Velocity Error:" in line:
            velerror.append(float(line[32:40]))
    if "Grid Dimensions, Mesh" in line:
            mesh.append(int(line[27]))
    if "Time Step  " in line:
            timestep.append(int(line[17:27].strip()))
    if "Total time:" in line:
            totaltime.append(float(line[47:57].strip()))
            i = i + 8
    i++

答案 2 :(得分:0)

从每个文件打印第n行

import glob
import numpy as np
import matplotlib.pyplot as plt
import math

velerror = []
divergence = []
mesh = []
timestep = []
totaltime = []
n_check = 5    # let n be 5

for files in glob.glob('*.out'):
    f = open(files, 'r')
    for i,line in enumerate(f):
        if "Maximum Velocity Error:" in line:
            velerror.append(float(line[32:40]))
        if "Grid Dimensions, Mesh" in line:
            mesh.append(int(line[27]))
        if "Time Step  " in line:
            timestep.append(int(line[17:27].strip()))
        if "Total time:" in line:
            totaltime.append(float(line[47:57].strip()))
        if not i%n_check:
            print(line)

答案 3 :(得分:0)

您可以使用关键字搜索该特定行,并打印第二个关键字的第n行。代码如下所示

search=open("test.txt",'r') 
for line in search:
   if "first_keyword" in line:
      while not "second_keywoed" in line:
          line=next(search)
      if "second_keyword" in line:
          print(line)

答案 4 :(得分:0)

您可以将linecache模块用于此

import linecache

line_count = 0
n_lines = 4  # just an example

for file in glob.glob('*.out'):
    with open(file, 'r') as f:
        for line in f:
            line_count += 1
            if "Maximum Velocity Error:" in line:
                velerror.append(float(line[32:40]))
            if "Grid Dimensions, Mesh" in line:
                mesh.append(int(line[27]))
            if "Time Step  " in line:
                timestep.append(int(line[17:27].strip()))
            if "Total time:" in line:
                totaltime.append(float(line[47:57].strip()))
                interesting_line = linecache.getline(file, line_count + n_lines)
                print(interesting_line)

答案 5 :(得分:0)

  

是否有像next()这样的函数进入下一行?

有一个功能 next(),它提供当前行并转到下一行。在包 itertools 中有一个函数 islice(),它构建了一个可迭代的子范围(即 next()的工作原理上)。幸运的是,你从 open()调用获得的文件句柄( f )也是可迭代的,所以你可以将这三个部分结合起来:

from itertools import islice
...
if "Total time:" in line:
  totaltime.append(float(line[47:57].strip()))
  #Print nth line after line
  # Skips to the 5th line, and stops and the 6th line;
  # counting begins at 0, so by human standards this
  # actually prints the 6th line:
  next_5th_line = next (islice (f, 5, 6))
  print (next_5th_line)

执行完之后,循环将在打印出的行之后继续,因此有些行将被简单地丢弃。