Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

使用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文件:
clipboard.png

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

clipboard.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

你代码根本地方错了 刚才我没看清楚

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

第二次直接是 []

读文件指针已经移动到底了 所以第二次没内容了啊

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

这样就可以了


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...