当我打开一个文本文件时,它只读取最后一个lin

2024-09-30 18:31:30 发布

您现在位置:Python中文网/ 问答频道 /正文

说自定义密码文件.txt里面有两条线。第一行是“123testing”,第二行是“testing321”。如果passwordCracking=“123testing”,那么输出的结果是“123testing”在文件中找不到(或类似的东西)。如果passwordCracking=“testing321”,那么输出将是在文件中找到“testing321”。我认为for循环只读取文本文件的最后一行。有解决办法吗?在

import time
import linecache

def solution_one(passwordCracking):
    print("Running Solution #1 @ " + time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
    startingTimeSeconds = time.time()
    currentLine = 1
    attempt = 1
    passwordFound = False
    wordListFile = open("customPassFile.txt", encoding="utf8")
    num_lines = sum(1 for line in open('customPassFile.txt'))
    while(passwordFound == False):
        for i, line in enumerate(wordListFile):
           if(i == currentLine):
                line = line
        passwordChecking = line
        if(passwordChecking == passwordCracking):
            passwordFound = True
            endingTimeSeconds = time.time()
            overallTimeSeconds = endingTimeSeconds - startingTimeSeconds
            print("~~~~~~~~~~~~~~~~~")
            print("Password Found: {}".format(passwordChecking))
            print("ATTEMPTS: {}".format(attempt))
            print("TIME TO FIND: {} seconds".format(overallTimeSeconds))
            wordListFile.close()
            break
        elif(currentLine == num_lines):
            print("~~~~~~~~~~~~~~~~~")
            print("Stopping Solution #1 @ " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            print("REASON: Password could not be cracked")
            print("ATTEMPTS: {}".format(attempt))
            break
        else:
            attempt = attempt + 1
            currentLine = currentLine + 1
            continue

Tags: 文件importtxtformatfortimelineprint
2条回答

代码的主要问题是打开文件并多次读取。第一次文件对象位置移到末尾并停留在那里。下次读取该文件时不会发生任何事情,因为您已经在文件的末尾。在

示例

有时候一个例子比很多词更有价值。 以文件test_file.txt为例,行如下:

line1
line2

现在打开文件并读两遍:

^{pr2}$

第二次什么都没有发生,因为文件对象已经在末尾。在

解决方案

这里有两个选项:

  1. 只读取一次该文件并将所有行保存在一个列表中,然后在代码中使用该列表。它应该足够替换了

    wordListFile = open("customPassFile.txt", encoding="utf8")
    num_lines = sum(1 for line in open('customPassFile.txt'))
    

    with open("customPassFile.txt", encoding="utf8") as f:
        wordListFile = f.readlines()
    num_lines = len(wordListFile)
    
  2. 在使用^{}读取文件后重置文件对象位置。这将是一条线索:

    for i, line in enumerate(wordListFile):
       if(i == currentLine):
            line = line
    wordListFile.seek(0)
    

我会选择选项1,除非你有内存限制(例如文件大于内存)

注释

我有一些额外的注释:

  • python以0(如c/c++)而不是1(如fortran)启动计数器。因此,您可能需要设置:

    currentLine = 0
    
  • 当您读取一个文件时,新行字符\n不会被删除,因此您必须(使用^{})执行此操作或在比较字符串时对其进行解释(例如使用^{})。例如:

    passwordChecking == passwordCracking
    

很可能总是返回False,因为passwordChecking包含{},而{}很可能没有

Discramer公司

我没有尝试过代码,也没有尝试过我的建议,所以可能有其他bug潜伏在周围。在

**我将在OP理解我理解他代码的意图的缩进中理解问题后删除此答案。*

for i, line in enumerate(wordListFile):
   if(i == currentLine):
        line = line
passwordChecking = line
#rest of the code.

这里您的代码在for循环之外,所以只缓存最后一行。在

^{pr2}$

相关问题 更多 >