将文件中的行放入多个变量中,从而造成怪异的不一致

时间:2019-04-02 14:50:49

标签: python file line

在我尝试解释这一点之前,这是我目前正在使用的代码:

currentLine = 1
try:
    with open(filename, 'r') as f:
        for line in f:
            if currentLine == 1:
                tempName = line
            if currentLine == 2:
                tempColour = line
            if currentLine == 3:
                tempAge = line
            if currentLine == 4:
                tempWeight = line
                currentLine = 1
                tempSheep = Sheep(tempName, tempColour, tempAge, tempWeight)
                sheepList.append(tempSheep)
            currentLine = currentLine + 1
except:
    print("file is in an invalid format")
    continue
else:
    break

代码的目标是从文件中读取4行(名称,颜色,年龄和重量)并将其放入Sheep对象。这需要循环执行,因为每个文件有2到10只羊。该代码大部分有效,因为它读取行并将其放入类中,但未读取正确的行。当我打印出所有绵羊时,每只绵羊都具有相同的名称“ bob”,这是文件中第一只绵羊的名称,也是第一行。除此之外,它实际上可以工作,但是它完全忽略了name变量,只是将bob放入其中。我最终遇到了这只名叫鲍勃的绵羊。

例如,示例输出如下:

Name: bob
Colour: blue
age: 5
weight: 50

name: bob
Colour: tina
age: red
Weight: 7

name: bob
colour: 75
age: shirley
Weight: green

以防它不明显,它通过忽略名称来抵消所有内容。我希望对此进行足够的解释,如果您需要进一步的解释,我可以尝试添加更多示例。

为什么我的程序不好?

2 个答案:

答案 0 :(得分:4)

        if currentLine == 4:
            tempWeight = line
            currentLine = 1
            tempSheep = Sheep(tempName, tempColour, tempAge, tempWeight)
            sheepList.append(tempSheep)
        currentLine = currentLine + 1

执行此if块时,最初会将currentLine设置为1。然后执行currentLine = currentLine + 1,将其设置为2。这意味着,当您再次到达循环顶部时,if currentLine == 1:检查将永远不会成功。

尝试将currentLine设置为零。

        if currentLine == 4:
            tempWeight = line
            currentLine = 0
            tempSheep = Sheep(tempName, tempColour, tempAge, tempWeight)
            sheepList.append(tempSheep)
        currentLine = currentLine + 1

...但是最好完全跳过if块。如果每条记录正好是四行,则可以使用How do you split a list into evenly sized chunks?中的一种配方来提取每条记录。然后,您可以通过参数解包将数据传递给Sheep构造函数。

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

with open(filename) as f:
    lines = [line.strip() for line in f]

sheepList = []
for group in chunks(lines, 4):
    sheepList.append(Sheep(*group))

答案 1 :(得分:1)

跟踪文件行的工作使事情变得有些棘手。您可以使用enumerate使事情变得简单一些,只需使用模运算符%将事物按5分组(每组名称以5行为一组):

for i, line in enumerate(f, start=1): # Start numbering at 1
    currentLine = i % 5 # At line 5, blank, this will be zero
    if not currentLine: # 0 acts as False
        continue

    # if elif else makes things a bit more efficient
    # as it's not possible for you to have multiple line number
    # possibilities
    if currentLine == 1:
       tempName = line
    elif currentLine == 2:
       tempColour = line
    elif currentLine == 3:
       tempAge = line
    else:
       tempWeight = line
       tempSheep = Sheep(tempName, tempColour, tempAge, tempWeight)
       sheepList.append(tempSheep)