0

Because file can't use in python 3.

In python 2, we judge a file type can do this:

with open("xxx.txt") as f:
    if isinstance(f, file):
        print("ok!")

In python 3, we can do this:

import io
with open("xxx.txt") as f:
    if isinstance(f, io.IOBase)
        print("ok!")

But the second code can't work in python 2.

So, is there a way to judge a file type both work in python 2 and python 3.

1 Answer 1

2

You can test for both with a tuple; use a NameError guard to make this work on Python 3:

import io

try:
    filetypes = (io.IOBase, file)
except NameError:
    filetypes = io.IOBase

isinstance(f, filetypes)

You need to test for both on Python 2 as you can use the io library there too.

However, it is better to use duck typing rather that testing for io.IOBase; see Check if object is file-like in Python for motivations. Better to check if the method you need is present:

if hasattr(f, 'read'):

Note that io.IOBase doesn't even include read. And in Python 2, StringIO.StringIO is a file-like object too, one that isinstance(.., file) will not support.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.