python - 使用readlines()方法读取文件内容后,再用for循环遍历文件与变量匹配时出现疑难?
PHP中文网
PHP中文网 2017-04-18 10:23:58
0
1
733

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中文网

认证高级PHP讲师

reply all(1)
Ty80

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!