2014-04-11 38 views
1

stackoverflow。file.read()在字符串比較中無法正常工作

我一直在試圖獲得下面的代碼來創建一個.txt文件,寫一些字符串,然後打印一些消息,如果說該字符串在文件中。這只是一個更復雜的項目的研究,但即使它簡單,它仍然無法正常工作。

代碼:

import io 

file = open("C:\\Users\\...\\txt.txt", "w+") #"..." is the rest of the file destination 
file.write('wololo') 

if "wololo" in file.read(): 
    print ("ok") 

此函數總是跳過如果因爲如果沒有「wololo」裏面的文件,即使我已經檢查了所有的時間,它有正常。

我不完全確定可能是什麼問題,我花了很多時間到處尋找解決方案,都無濟於事。這個簡單的代碼有什麼可能是錯的?

哦,如果我要在一個更大的.txt文件中搜索字符串,使用file.read()會是明智的嗎?

謝謝!

回答

3

當您寫入文件時,光標將移動到文件的末尾。如果你想讀取數據aferwards,你必須將光標移動到文件的開頭,如:

file = open("txt.txt", "w+") 
file.write('wololo') 

file.seek(0) 
if "wololo" in file.read(): 
    print ("ok") 
file.close() # Remember to close the file 

如果該文件是大,你應該考慮遍歷由文件行行代替。這將避免整個文件存儲在內存中。還要考慮使用上下文管理器(關鍵字with),以便您不必親自顯式關閉文件。

with open('bigdata.txt', 'rb') as ifile: # Use rb mode in Windows for reading 
    for line in ifile: 
     if 'wololo' in line: 
      print('OK') 
    else: 
     print('String not in file')