Aleeee
Aleeee

Reputation: 2023

How to judge a file type both work in python 2 and python 3

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.

Upvotes: 0

Views: 986

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121406

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.

Upvotes: 2

Related Questions