我有 2 个文件,密码和字典。 passwd 是一个只有一个单词的测试文件,而字典则有几行单词的列表。到目前为止,我的程序仅读取和比较字典文件的第一行。例如。我的字典文件包含(鸡蛋、鱼、红色、蓝色)。我的 passwd 文件仅包含(egg)。
程序运行得很好,但是一旦我将字典文件中的单词 Egg 切换为列表中的最后一个,程序就不会读取它,也不会提取结果。
我的代码如下。
#!/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()
最佳答案
如果你这样做
for line in file_obj:
....
您正在隐式使用 readline
文件的方法,每次调用都会推进文件指针。这意味着内循环第一次完成后,将不再执行,因为没有更多的行可以读取。
一种可能的解决方案是使用 readlines
在内存中保留一个(最好是较小的)文件。 。这样,您就可以对从其他文件读取的每一行进行迭代。
file_as_list = file_obj.readlines()
for line in file_obj_2:
for line in file_as_list:
..
关于python - 如何让Python程序读取文件中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28130926/