Read TXT file line by line

This question already has an answer here:

  • In Python, how do I read a file line-by-line into a list? 35 answers

  • readlines returns a list of strings with all remaining lines in the file. As the python docs state you could also use list(inFile) to read all ines (https://docs.python.org/3.6/tutorial/inputoutput.html#methods-of-file-objects)

    But your problem is that python reads the line including the newline character ( n ). And only the last line has no newline in your file. So by comparing guess == real you compare 'password1n' == 'password1' which is False

    To remove the newlines use rstrip :

    chars = [line.rstrip('n') for line in inFile]
    

    this line instead of:

    chars = inFile.readlines()
    

    First of all try to search duplicated posts.

    How do I read a file line-by-line into a list?

    For example, what I am usually using when working txt files:

    lines = [line.rstrip('n') for line in open('filename')]
    
    链接地址: http://www.djcxy.com/p/42346.html

    上一篇: 从文件中读取用户名和密码

    下一篇: 逐行读取TXT文件