0
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)

我试图在找到“位置:”行时一次读取文件四行,但由于返回语句结束循环,这仅输出前四行。

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

4

2 回答 2

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)]
于 2013-10-16T10:22:23.887 回答
0

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

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.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

导入BLB(文件路径)

于 2013-10-16T19:23:03.920 回答