How do you check if an object is an instance of a "file"?

It used to be in Python (2.6), which one might ask:

isinstance(f, file)

but in Python 3.0 has filebeen removed .

What is the correct method to check if a variable is a file now? Whatsnew docs don't mention it ...

+3
source share
4 answers
def read_a_file(f)
    try:
        contents = f.read()
    except AttributeError:
        # f is not a file

replace all the methods you plan to use for read. This is optimal if you expect to get a file similar to an object in more than 98% of cases. If you expect that an object that does not look like a file will be passed to you more than 2% of the time, then the right thing is:

def read_a_file(f):
    if hasattr(f, 'read'):
        contents = f.read()
    else:
        # f is not a file

, , file . ( FWIW, file 2.6). , 3.x.

+5

python3 io file

import io
isinstance(f, io.IOBase)
+4

, , , , f.read() - , , , json.load() AttributeError, , read.

; hasattr/getattr:

def read(file_or_filename):
    readfile = getattr(file_or_filename, 'read', None)
    if readfile is not None: # got file
       return readfile()
    with open(file_or_filename) as file: # got filename
       return file.read()

, file_of_filename read, None, try/except over file_or_filename.read - : no parens, - , ElementTree._get_writer().

, , (io.RawIOBase.read(n) n > 0) (io.BufferedIOBase.write()) / ( io.TextIOBase), isinstance() ABC, io, , saxutils._gettextwriter() .

0

python 2.6... , - del file - ?

-3

Source: https://habr.com/ru/post/1766316/


All Articles