尝试从文件读取时,对象没有属性错误

时间:2017-07-29 19:17:58

标签: python-3.x attributes

我试图用来自用户的输入来代码替换文件中的字符串。我一直得到错误builtins.AttributeError:' str'对象没有属性' read'导致此错误的原因是什么?据我所知,语法应该是正确的。我虽然对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 个答案:

答案 0 :(得分:1)

您需要一个文件处理程序。你不能直接在文件名上使用read方法。

例如

fh = open(filename, 'r')
data = fh.readlines()