Skip to content

Instantly share code, notes, and snippets.

@joshkautz
Created September 27, 2016 15:57
Show Gist options
  • Save joshkautz/fc0df380f5e727dce7b0fb1f7cae7d7e to your computer and use it in GitHub Desktop.
Save joshkautz/fc0df380f5e727dce7b0fb1f7cae7d7e to your computer and use it in GitHub Desktop.
Python script to download the contents of tables from a database to a local file, and backing up existing file if it exists.
#!/usr/bin/python
import sys
import os
from pathlib import Path
import sqlite3
from shutil import copyfile
# Takes the filename of the script, converts it to an absolute path.
# Then extracts the directory of that path, then changes into that directory.
# This results in the creation of the output file to always be in the same directory as the script.
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
# Prints the number and list of arguments.
print ("Number of arguments: ", len(sys.argv), "arguments.")
print ("Argument List:", str(sys.argv))
print ("SQLite3 Version: ",sqlite3.version,"\n")
# Checks to see if file exists.
# If file exists, copy to a backup file, then erase contents.
# Otherwise, create file.
file = Path(dname + "/database.txt")
if file.is_file():
print("File exists.\n")
print("Coping file.\n")
copyfile(str(file), str(dname + "\database_BACKUP.txt"))
with open("database.txt", "w"):
pass
else:
print("File does not exist.\n")
print("Creating file.\n")
with open('database.txt', 'w+') as f:
for line in f:
print(line)
f.write("")
f.close()
# Begin database interaction
conn = sqlite3.connect()
cur = conn.cursor()
tables=["tablename1","tablename2","tablename3","tablename4"]
for table in tables:
cur.execute("SELECT * FROM ?", table)
rows = cur.fetchall()
# Append database table contents to file
with open('database.txt', 'a') as f:
f.write(rows)
f.close()
conn.commit()
conn.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment