python - 如何让Python程序读取文件中的行

标签 python linux dictionary passwords crypt

我有 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/

相关文章:

python - Pandas :如何按列和索引对数据框进行排序

python - M1 Mac : Running Brownie Python

linux - wc -l on unix 命令返回值

python - 从 JSON 记录(字典)创建对象

Python,将字典添加到JSON文件

python - 将.crx加载到远程chrome Selenium python中

android - 从 Android 手机发送命令到 Linux 桌面

linux - MongoDB 数据库从一个操作系统迁移到另一个操作系统

iOS:使用 for-in 循环管理 Dictionray 数据

python - python程序中出现 "List Reversing"错误