我试着从一个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循环跳过单词表.txt文件,如果不为空,则将它们添加到单词列表中。但是,由于某些奇怪的原因,它不喜欢前三行,并将它们作为空行放入变量中。为什么会这样?当然,它们不是世界上最重要的词,但我还是希望它能用上它们。在
首先,调用^{} 检查行是否为空:
因为您使用
size=i
来调用它,所以最多只能读取i
个字符。第一行是0。对于其他每一行,它都大于0,所以它不会再次触发(除非您到达EOF),因为一行总是至少有一个字符(换行符)。在然后,如果没有触发,那么就不用读到的行,而是读另一行:
^{pr2}$尽管您可能没有读整行,因为您传递了一个
size
参数。在然后你又读到另一行:
所以,你切断了所有早期行的开头,跳过了几乎三分之二的行,而不把它们添加到列表中,你的空测试实际上只是测试是否是第一行。在
您可能需要做的是调用
readline()
而不是一行三次,而不是一次调用。在或者,最好直接迭代该文件,就像在代码顶部处理另一个文件一样。在
我不知道你为什么要停在185051线,但我想是有原因的。所以,与其
enumerate
这些行,不如zip
它们有一个范围:相关问题 更多 >
编程相关推荐