Home  >  Q&A  >  body text

python - 使用readlines()方法读取文件内容后,再用for循环遍历文件与变量匹配时出现疑难?

with open('password', 'r', encoding='utf-8') as f:

print(f.readlines())
for i in f.readlines():
    if i == 'abc:cba':
        break
else:
    print('none')

这是password文件:

想起到的作用是for循环时,匹配到对应的值就跳出循环,但是每次都没法匹配到。
下图是输出结果

PHP中文网PHP中文网2740 days ago735

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:25:58

    Your code is fundamentally wrong. I didn’t see it clearly just now

    with open('password', 'r', encoding='utf-8') as f:
        print(f.readlines())
        print(f.readlines())

    The second time is directly []

    The read file pointer has moved to the end, so there is no content for the second time

    with open('password', 'r', encoding='utf-8') as f:
        # print(f.readlines())
        # print(f.readlines())
        readlines = f.readlines()
        print(readlines)
        for i in readlines:
            if i.strip() == 'abc:cba':
                break
        else:
            print('none')
      

    That’s it

    reply
    0
  • Cancelreply