错误:无法调用'_io.TextIOWrapper'对象

问题描述

我写了一段代码,用二等分法找到方程的根。
我试图在循环的每次迭代中添加循环索引和两个解决方案之间的差异,但是我遇到了问题标题中提到的错误

此外,我看到了类似问题的答案,人们已经建议使用write方法而不是直接调用它,这给了我一个错误,说 'builtin_function_or_method' object has no attribute 'write'

我的代码:-

#Function to solve by bisection method
def bisection(f,a,b,fileName,tol = 10**-6):
    #making sure a is left of b
    if(a>b):
        temp = b
        b = a
        a = temp
    
    #Bracketing the roots
    a,b = bracketChecker(f,b)
    if((a,b) == False): return None

    #Checking if either of a or b is a root
    if(f(a)*f(b) == 0):
        if(f(a)==0):
            return a
        else: return b

    else:
        i = 0
        c = 0
        while(abs(a-b) > tol and i<200):
            c_old = c
            c = (a+b)/2.0
            abserr = c - c_old
            if (abs(f(c)) < tol):
                return c
            if (f(a)*f(c)<0):
                b = c
            else: a = c

            #Appending the data
            with open(fileName,'a') as f:
                print(i,abserr,file=f)             #The error is occuring here
            i += 1
    return (a+b)/2.0

解决方法

它工作正常,仅因为我将文件命名为f才出现问题,这与我用于函数的变量相同。因此,错误... 谢谢@mibu指出了这一点