【问题标题】:Read TXT file line by line - Python [duplicate]逐行读取TXT文件-Python [重复]
【发布时间】:2017-08-29 15:05:24
【问题描述】:

如何告诉 python 逐行读取 txt 列表? 我正在使用 .readlines() 似乎不起作用。

import itertools
import string
def guess_password(real):
    inFile = open('test.txt', 'r')
    chars = inFile.readlines()
    attempts = 0
    for password_length in range(1, 9):
        for guess in itertools.product(chars, repeat=password_length):
            attempts += 1
            guess = ''.join(guess)
            if guess == real:
                return input('password is {}. found in {} guesses.'.format(guess, attempts))
        print(guess, attempts)

print(guess_password(input("Enter password")))

test.txt 文件如下所示:

1:password1
2:password2
3:password3
4:password4

目前该程序仅适用于列表中的最后一个密码 (password4) 如果输入任何其他密码,它将运行列表中的所有密码并返回“无”。

所以我假设我应该告诉 python 一次测试每一行?

PS。 “return input()”是一个输入,所以对话框不会自动关闭,没有什么可输入的。

【问题讨论】:

  • 我有点担心您似乎存储纯文本密码。
  • @TomdeGeus 你的陈述绝对有效,但如果我猜的话,这可能是一个练习,而不是一个真正的应用程序。

标签: python list python-3.x brute-force


【解决方案1】:

readlines 返回文件中所有剩余行的字符串列表。正如 python 文档所述,您还可以使用 list(inFile) 来读取所有 ines (https://docs.python.org/3.6/tutorial/inputoutput.html#methods-of-file-objects)

但您的问题是 python 读取包含换行符 (\n) 的行。只有最后一行在您的文件中没有换行符。所以通过比较 guess == real 你比较 'password1\n' == 'password1' 这是False

要删除换行符,请使用rstrip:

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

这一行代替:

chars = inFile.readlines()

【讨论】:

    【解决方案2】:

    首先尝试搜索重复的帖子。

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

    例如,我在处理txt文件时通常使用的:

    lines = [line.rstrip('\n') for line in open('filename')]
    

    【讨论】:

      猜你喜欢
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 2015-08-20
      • 2019-04-24
      相关资源
      最近更新 更多