2017-07-29 32 views
1

我試圖用用戶的輸入替換文件中的字符串。我不斷收到錯誤builtins.AttributeError:'str'對象沒有屬性'讀'是什麼導致這個錯誤?據我所知,語法應該是正確的。雖然我對Python仍然很陌生。當試圖從文件讀取時,對象沒有屬性錯誤

我的代碼是:

import os 


filename = input('Enter a filename: ') 
old = input('Enter the old string to be replaced: ') 
new = input('Enter the new string to replace the old string: ') 

os.path.isfile(filename) 

data = '' 
open(filename, 'r') 
data += filename.read().replace(old, new) 
filename.close() 

open(filename, 'w') 
filename.write(data) 
filename.close() 
print('Done') 

回答

1

你需要一個文件處理程序。您不能直接在文件名上使用讀取方法。

對於e.g

fh = open(filename, 'r') 
data = fh.readlines() 
相關問題