NameError: name 'file' 未定义为 isinstance 参数

问题描述

我目前正在调试一个代码,我遇到了一个与其他条目不同的“NameError: name 'file' is not defined”问题,我的问题是因为 isinstance 函数不理解“文件参数” "

def write_param_file(f,molfile,name,frag_id,base_confs,max_confs,amino_acid=None): #{{{
    '''Writes a Molfile object to a file.
    f may be a file name or file handle.
    base_confs is the number of heavy-atom conformations generated by e.g. Omega
    max_confs is the maximum number of conformations desired after adding proton rotation
        The total number of confs may still be larger than max_confs,but at least we'll skip -ex# extra sampling of proton chis.
    '''
    close_file = False
    if not isinstance(f,file):
        f = open(f,'w')
        close_file = True

isinstance 函数需要两个必须是元组的参数。正如你所看到的,“f”被定义了。但“文件”不是。我认为这个问题有一个简单的解决方案,所以如果你能提供帮助,那将非常有帮助。

解决方法

文件是 python 2 中的现有类型,但不是 python 3。使用 python 2 运行此代码或使用以下链接中的信息对其进行调整。

isinstance file python 2.7 and 3.5