2017-07-29 69 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() 
相关问题