Search code examples
pythonlinuxdictionarypasswordscrypt

How can I make Python program read line in file


I have 2 files, passwd and dictionary. The passwd is a test file with one word, while the dictionary has a list of a few lines of words. My program so far reads and compares only the first line of the dictionary file. For example. My dictionary file contain (egg, fish, red, blue). My passwd file contains only (egg).

The program runs just fine, but once I switch the word egg in the dictionary file to lets say last in the list, the program wont read it and wont pull up results.

My code is below.

#!/usr/bin/passwd

import crypt

def testPass(line):
    e =  crypt.crypt(line,"HX")
    print e

def main():
    dictionary = open('dictionary', 'r')
    password = open('passwd', 'r')
    for line in dictionary:
        for line2 in password:
            if line == line2:
                testPass(line2)
    dictionary.close()
    password.close()

main()

Solution

  • If you do

    for line in file_obj:
      ....
    

    you are implicitly using the readline method of the file, advancing the file pointer with each call. This means that after the inner loop is done for the first time, it will no longer be executed, because there are no more lines to read.

    One possible solution is to keep one -- preferably the smaller -- file in memory using readlines. This way, you can iterate over it for each line you read from the other file.

    file_as_list = file_obj.readlines()
    for line in file_obj_2:
      for line in file_as_list:
        ..