0

I'm currently debugging a code and I've bumped into a "NameError: name 'file' is not defined" problem different from other entries, my problem is caused because the isinstance function doesn't understand the "file parameter"

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

the isinstance function wants two arguments that must be tuples. And as you can see "f" is defined. But "file" is not. I think there is an easy solution to this problem so if you can help it would be very helpful.

  • Does this answer your question? [Check if object is file-like in Python](https://stackoverflow.com/questions/1661262/check-if-object-is-file-like-in-python) – rdas Jan 19 '21 at 11:40
  • another option is to check if the following is true `type(f) is io.TextIOWrapper` (this only works for reading in text mode, in binary mode its io.BufferedRead) – Nullman Jan 19 '21 at 11:44
  • 1
    This error has nothing to do with the `isinstance` function, the error happens *before* that function is called, when the interpreter tries to resolve the name of the argument. `file` deosn't exist. Was this code written for Python 2? – juanpa.arrivillaga Jan 19 '21 at 11:46
  • In this case, you should probably just check if it is a string. – juanpa.arrivillaga Jan 19 '21 at 11:47
  • You could use `os.path.isfile()` from the 'os' module. – Ghoti Jan 19 '21 at 20:50

1 Answers1

0

File is an existing type in python 2 but not in python 3. Run this code with python 2 or adapt it with information from the link below.

isinstance file python 2.7 and 3.5

Pallie
  • 965
  • 5
  • 10