2014-01-21 46 views
0

以下函數應該打印200行,而只打印「[]」。我不完全確定我在這裏出了什麼問題,並希望有一雙新的眼睛能夠幫助我。islice怎麼只打印[]?

謝謝!

def main(): 
from itertools import islice 
userfile = raw_input("Please enter the file you wish to open\n(must be in this directory): ") 
file1 = open(userfile, "r+") 
jcardtop = file1.read(221); 
#print jcardtop 
n = 200 
while True: 
    next_n_lines = list(islice(file1,n)) 
    if not next_n_lines: 
     break 
print next_n_lines 
+1

你肯定'file1'有更多的線,你已經閱讀了第一221個字節之後? – mgilson

+0

@IanAuld:你真的不應該修改後修復縮進錯誤時,問題幾乎可以肯定是由壓痕引起... – abarnert

回答

2

如果你的代碼實際上看起來你貼什麼:

while True: 
    next_n_lines = list(islice(file1,n)) 
    if not next_n_lines: 
     break 
print next_n_lines 

...那麼,問題是,你不print什麼,直到循環完成,這意味着你只打印了最後一片,根據定義,這是空的。

如果你的代碼樣子,在文本編輯器,它可以仍然看起來像Python的,因爲你可能會被混合製表符和空格。嘗試使用更好的文本編輯器 - 幾乎除了記事本或文本編輯器以外的任何東西都可以選擇將製表符轉換爲空格,或者可視化地顯示製表符。或者用Python的-tt標誌運行腳本。

+0

真棒即固定它,謝謝! 我會在9分鐘內將您標記爲已接受的答案。 – Mason