【发布时间】: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