for循环的顺序会影响结果

时间:2019-06-12 20:23:16

标签: python

运行以下代码时。仅循环1将被执行,循环2消失了。但是,如果我将循环1移到循环2之后,则将执行两个循环。这是为什么 ? 谢谢

stdenv.mkDerivation {
  name = "Env";
  buildInputs = [ nix git bash python ]; 
...

1 个答案:

答案 0 :(得分:2)

这是因为您已经在第一个循环中使用了文件句柄。一个简单的例子可能是:

with open('afile.txt') as fh:
    # this will consume fh
    for line in fh:
        print(line)

    print(fh.readline()) # prints empty string, because there's nothing left to read

    for line in fh:
        print(line) # won't do anything because you've already read everything

如果要两次读取文件,可以使用fh.seek(0)返回到开头:

with open('afile.txt') as fh:
    for line in fh:
        print(line)

    fh.seek(0)
    # now this works
    for line in fh:
        print(line)