一次读取文件4行

时间:2013-10-16 10:13:47

标签: python file while-loop lines

import os
filePath = "C:\\Users\\siba\\Desktop\\1x1x1.blb"
BrickName = (os.path.splitext(os.path.basename(filePath))[0])

import sys
def ImportBLB(filePath):
    file = open(filePath)
    line = file.readline()

    while line:
        if(line == "POSITION:\n"):
            POS1 = file.next()
            POS2 = file.next()
            POS3 = file.next()
            POS4 = file.next()
            sys.stdout.write(POS1)
            sys.stdout.write(POS2)
            sys.stdout.write(POS3)
            sys.stdout.write(POS4)
            return

        line = file.readline()
    file.close()
    return

ImportBLB(filePath)

我试图在找到“POSITION:”行时一次读取文件四行,但这只会输出前四行,因为return语句结束了循环。

删除return语句会给我一个“ValueError:混合迭代和读取方法会丢失数据”错误,我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

用这个替换你的逻辑:

with open(file_path) as f:
    while True:
        try:
            line = next(f)
        except StopIteration:
            break # stops the moment you finish reading the file
        if not line:
            break # stops the moment you get to an empty line
        if line == "POSITION:\n":
            for _ in range(4):
                sys.stdout.write(next(f))

编辑:根据您的评论说明,您需要4个变量;每行1个。用这个代替最后一部分:

lines = [next(f) for _ in range(4)]

如果您更喜欢单个变量,这将为您提供包含4个项目(您想要的4行)的列表:

line1, line2, line3, line4 = [next(f) for _ in range(4)]

答案 1 :(得分:0)

使用了上述两个建议,现在是我的代码;

导入操作系统 filePath =“C:\ Users \ siba \ Desktop \ 1x1x1.blb” BrickName =(os.path.splitext(os.path.basename(filePath))[0])

导入系统 def ImportBLB(filePath):     file = open(filePath)     line = file.next()

while line:
    if(line == "POSITION:\n"):
        POS1 = file.next()
        POS2 = file.next()
        POS3 = file.next()
        POS4 = file.next()
        sys.stdout.write(POS1)
        sys.stdout.write(POS2)
        sys.stdout.write(POS3)
        sys.stdout.write(POS4)

    try:
        line = file.next()
    except StopIteration:
        break
file.close()
return

ImportBLB(文件路径)