How to check if a file is Database file or not in Python

In Python, we use the sqlite3 module to work with databases. In sqlite3 the method connect() method will create a new database if one already does not exist.

You might be trying to check if a database file already exists, to prevent the connect() function from creating a database.

In this python tutorial, I will guide you to check if a database file already exists or not. You will be able to see if a file is a database file or not.

Check if a file is SQLite file or not in Python

The official way to check if a file is SQLite file or not is to use the python os module and check the header of the file.

Below is the python code that checks the header of the file. This will tell you if a file is actually a database file or not.


def isSQLite3(filename):
    from os.path import isfile, getsize
    if not isfile(filename):
        return False
    if getsize(filename)< 100: # SQLite database file header is 100 bytes
        return False

    with open(filename, 'rb') as fd:
        header = fd.read(100)

    return header[:16] == 'SQLite format 3\x00'

isSQLite3('db.sqlite')

Output:

The file db.sqlite is actually a SQLite file. so it will return true. You can check this code in your Python Ide.

If you have a bunch of files you can iterate through the file and check each one if for loop as well.


for file in files:
    if isSQLite3(file):
        print "'%s' is a SQLite3 database file" % file
    else:
        print "'%s' is not a SQLite3 database file" % file

Method No 2 To check if a file is actually sqlite file or not in python

We have used the os module and sys module to check if a file is a database file or not. This is a reliable way to check if the file is SQLite file or not in python.


import os
import sys

if os.path.isfile('test.sqlite3'):
    if os.path.getsize('test.sqlite3') > 100:
        with open('test.sqlite3','r', encoding = "ISO-8859-1") as f:
            header = f.read(100)
            if header.startswith('SQLite format 3'):
                print("SQLite3 database has been detected.")

Summary and Conclusion

In this python tutorial, we have seen two different ways to see if a file is SQLite file or not. In the first method we have used the header of the file. while in the second method we have checked the encoding and also the header.

Leave a Comment

Scroll to Top