2016-10-18 41 views
0

我想寫一個文本閱讀器程序,可以將文本分爲三部分:標題,標記和內容。爲什麼在python中讀取文本時會出現拖尾?

發生什麼事情是它在內容的每一端給我一個「無」值。

這裏是內容讀碼:

#counting lines in the text 
def bufcount(file): 
    file.seek(0) 
    lines = 0 
    buf_size = 1024 * 1024 
    read_f = file.read # loop optimization 

    buf = read_f(buf_size) 
    while buf: 
     lines += buf.count('\n') 
     buf = read_f(buf_size) 
    return lines 

#for reading the content 
def searchForTheContent(file): 
    count=bufcount(file) 
    file.seek(0) 
    i=3 #to read after the third line, which is the content 
    lines=file.readlines() 
    while i<count: 
     i=i+1 
     #print(i) 
     if lines[i]=="\n": 
      pass 
     if lines[i]!="\n": 
      print(lines[i]) 

調用該函數:

path= '.\\Texts\\*.txt' 
files = glob.glob(path) 

for name in files: 
    file= open(name) 
    print(searchForTheContent(file)) 

結果:

safahsdfhajfha 
dfasdfsdfsadf 

sadfasdfasdfasdfasdf 

asdfasfdasd 
None 

剛纔那個 '無' 價值從何而來?和任何建議如何刪除它?

+2

'None'不是來自您在此顯示的代碼。你如何調用searchforTheContent()函數?你有沒有使用'print(searchForTheContent(filename))'? –

+0

它是這樣的: print(searchForTheContent(file)) – JoanLamrack

+0

那麼,因爲'searchForTheContent()'返回'None',所以你正在打印返回值*。 –

回答

3

您打印該函數的返回值:

print(searchForTheContent(file)) 

searchForTheContent()沒有明確return語句,所以None返回,並且要打印的是。你會得到相同的結果用一個空函數:

>>> def foo(): pass 
... 
>>> print(foo()) 
None 

刪除print()電話:

for name in files: 
    file= open(name) 
    searchForTheContent(file) 

只要是明確的:print()沒有「返回」任何東西給調用者; print()將輸出發送到stdout流,該流通常連接到您的終端,這就是您在那裏看到輸出的原因。該輸出也不作爲返回值給出。

+0

啊,好吧,這解釋了很多。謝謝。 – JoanLamrack

相關問題