python - 如何在 python 2.6 中处理特定行之后的数据?

标签 python

我有一个脚本,它基本上读取一个文本文件并创建 8 个列表。如果它从第 1 行读取文件,它就可以完美工作。我需要它从第 177 行到第 352 行(即最后一行)开始读取文本文件。

这是我的脚本和更改。我没有收到任何错误,但也没有任何结果。程序卡在那里没有响应:

f = open("Output1.txt", "r")

lines = [line.rstrip() for line in f if line != "\n"] #Get all lines, strip
newline chars, and remove lines that are just newlines.


NUM_LISTS = 8

groups = [[] for i in range(NUM_LISTS)]



listIndex = 0


for line in lines:


    while line > 177: #here is the problem


        if "Transactions/Sec for Group" not in line:
            groups[listIndex].append(float(line))
            listIndex += 1
            if listIndex == NUM_LISTS:
                listIndex = 0
                value0 = groups[0]
                value1 = groups[1]
                value2 = groups[2]
                value3 = groups[3]
                value4 = groups[4]
                value5 = groups[5]
                value6 = groups[6]
                value7 = groups[7]



json_file = 'json_global.json'

json_data = open(json_file)

data = json.load(json_data)

for var1 in range(0, 11):

    a = value0[var1]
    b = value1[var1]
    c = value2[var1]
    d = value3[var1]
    e = value4[var1]
    f = value5[var1]
    g = value6[var1]
    h = value7[var1]

    var2 = var1 + 57

    item = data[var2]['item']

    cmd = data[var2]['command']


    var1+= 1

    print item, cmd,  a, b, c, d, e, f, g, h)

最佳答案

line 包含每行的内容,而不是行号。即使确实如此,这也会失败,因为您会跳过循环,因为第一行的数字不大于 177。这是一种执行您想要的操作的方法:

for linenumber, line in enumerate(lines, 1):
    if linenumber > 177:
        do_stuff(line)

enumerate() 接受一个可迭代对象并返回一个由 (index, item) 元组组成的可迭代对象。 1 参数告诉它从哪个索引开始;默认为0。根据您想要执行的操作调整该值和 if linenumber > 177: 中的数字。

另一种方法是使用 itertools.islice(),正如Anand S Kumar 中也提到的那样。在 his answer 。这是使用 islice() 的版本,它不会事先将整个文件读入内存:

from itertools import islice

with open('Output1.txt', 'r') as f:
    lines = (line.rstrip() for line in f if line != '\n')
    for line in islice(lines, 177, None):
        do_stuff(line)

这将有效地对行进行切片,就像您完成了lines[177:](这是另一种解决方案)一样。

请注意,您不包括仅换行符的行,因此文件中的第 177 行与程序中的第 177 行不同。

关于python - 如何在 python 2.6 中处理特定行之后的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32262880/

相关文章:

python - 如何通过 telegra.ph API 使用 HTML 格式

python - numpy.empty() 返回的值是否随机?

python - 使用 Python 打开新窗口时,selenium window_handles 不正确

python - 在 Python 3 中将字节转换为可读字符串

python - 无法在 OpenCV 中更改框架高度和宽度

python - Raspberry Pi 上的按钮交互

python - 无法在打开端口转发的另一台 PC 上访问 MySQL 数据库

python - 类型错误 : inputNames() takes no arguments (2 given)

python - Django CreateView 类如何实例化模型?

python - Tkinter 按钮距窗口边缘的距离