[英]Why can't I access list element
我正在嘗試從令牌變量訪問列表元素,但我不斷收到錯誤消息
print token[0]
IndexError: list index out of range'
當我嘗試從令牌列表訪問元素時。
文件變基文件的內容為:
ZraI 3 GAC'GTC 0 ! AatII >INV
;ZrmI 3 AGT'ACT 0 ! ScaI,AssI,BmcAI >I
代碼是:
with open (rebase_file, 'r') as rebase:
lines = rebase.readlines()
string = ''
for line in lines:
token = line.split()
print token[0]
您遇到了空行:
>>> ''.split()[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
只需使用if line.strip():
:
with open (rebase_file, 'r') as rebase:
for line in rebase:
if line.strip():
token = line.split()
print token[0]
請注意,我直接循環遍歷該文件,而不是一次全部將其讀入內存。
您可能有一個空行,請檢查一下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.