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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Aleeee
  • 1,913
  • 6
  • 17
  • 27

1 Answers1

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.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343