簡體   English   中英

Python 3通過readline將空字符串添加到列表

[英]Python 3 adding empty strings to list via readline

我正在嘗試從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來檢查該行是否為空:

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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM