我想寫一個文本閱讀器程序,可以將文本分爲三部分:標題,標記和內容。爲什麼在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
剛纔那個 '無' 價值從何而來?和任何建議如何刪除它?
'None'不是來自您在此顯示的代碼。你如何調用searchforTheContent()函數?你有沒有使用'print(searchForTheContent(filename))'? –
它是這樣的: print(searchForTheContent(file)) – JoanLamrack
那麼,因爲'searchForTheContent()'返回'None',所以你正在打印返回值*。 –