【问题标题】:Python 3 adding empty strings to list via readlinePython 3 通过 readline 将空字符串添加到列表中
【发布时间】:2018-08-07 21:21:13
【问题描述】:

我正在尝试从 txt 文件中获取并将它们放入变量中。这是我的代码:

#file_len function, got it from somewhere on stack exchange
def file_len(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1
#various variables, containing names/files
#wordList File, stores all the words
wordListFileName = '/Users/k/Desktop/Cyber/HashCrack/wordlist.txt'
wordListFile = open(wordListFileName)
#wordList list, stores all the words from the wordList file
wordList = []
#passList file, stores all the passwords
passListFileName = '/Users/k/Desktop/Cyber/HashCrack/passlist.txt'
passListFile = open(passListFileName, 'w')
#for loop, gets all the words in the wordList file, stores them in wordList list
for i in range(0, 185051):
if wordListFile.readline(i) == '':
    print('skipped empty line ' + str(i))
else:
    wordList.append(wordListFile.readline(i).strip('\n'))
    print('added ' + wordListFile.readline(i).strip('\n') + ' to wordList under number ' + str(i) + ' and word ' + wordList[i-1])

因此,for 循环会跳过 wordlist.txt 文件中的所有空行,如果它们不为空,则将它们添加到 wordList 列表中。但是,由于某些奇怪的原因,它不喜欢前三行并将它们作为空行放入变量中。为什么这样做?当然,它们不是世界上最重要的词,但我仍然希望使用它们。

【问题讨论】:

  • 您的标签当前不正确。另外,请删除与您的问题无关的任何代码
  • 我相信readline 不会像您认为的那样做。你觉得i在这里是什么意思?
  • 你的 for 循环是错误的。当您执行 readline(i) 时,您在第一轮中读取 0 行,在第二轮中读取 1 行,在第三轮中读取 2 行。在 Python 中你可以简单地做: for line in wordListFile:
  • @nauer readline 也不会像认为的那样做。
  • 非常感谢@abarnert,就是这样!我认为 readline() 函数有点愚蠢。为什么你不能指定一个特定的行,也许在那之后,检查字符?无论如何,非常感谢。我刚开始使用python。还有,zip函数有什么作用?

标签: python string python-3.x for-loop


【解决方案1】:

首先,您调用readline 来检查该行是否为空:

if wordListFile.readline(i) == '':
    print('skipped empty line ' + str(i))

由于您使用size=i 调用它,因此您最多读取i 个字符。对于第一行,它是 0。对于其他每一行,它都大于 0,所以这永远不会再次触发(除非你达到 EOF),因为一行总是至少有一个字符(换行符)。

然后,如果这没有触发,那么您阅读另一行,而不是使用您阅读的那一行:

wordList.append(wordListFile.readline(i).strip('\n'))

尽管您可能没有阅读整行,因为您传递了 size 参数。

然后你又读到另一行:

print('added ' + wordListFile.readline(i).strip('\n') + ' to wordList under number ' + str(i) + ' and word ' + wordList[i-1])

因此,您正在切断所有早期行的开头,并通过阅读它们而不将它们添加到列表中来跳过几乎三分之二的行,而您的空虚测试实际上只是测试第一行.


您可能想要做的只是调用readline() 而不指定大小,并且只调用一次而不是连续三次。

或者,更好的是,直接迭代文件,就像在代码顶部处理其他文件一样。

我不确定您为什么要停在 185051 行,但我认为是有原因的。所以,不是enumerate 行,让我们zip 给他们一个范围:

for i, line in zip(range(185051), wordListFile):
    line = line.strip('\n')
    if not line:
        print('skipped empty line ' + str(i))
    else:
        wordList.append(line)
        print('added ' + line + ' to wordList under number ' + str(i) + ' and word ' + wordList[i-1])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 2018-11-27
    • 2016-02-26
    • 2023-02-15
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多