Created
September 27, 2016 15:57
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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