· 10 years ago · Sep 27, 2016, 08:42 PM
1#!/usr/bin/python
2
3import sys
4import os
5from pathlib import Path
6import sqlite3
7from shutil import copyfile
8
9# Takes the filename of the script, converts it to an absolute path.
10# Then extracts the directory of that path, then changes into that directory.
11# This results in the creation of the output file to always be in the same directory as the script.
12abspath = os.path.abspath(__file__)
13dname = os.path.dirname(abspath)
14os.chdir(dname)
15
16
17# Prints the number and list of arguments.
18print ("Number of arguments: ", len(sys.argv), "arguments.")
19print ("Argument List:", str(sys.argv))
20print ("SQLite3 Version: ",sqlite3.version,"\n")
21
22
23# Checks to see if file exists.
24# If file exists, copy to a backup file, then erase contents.
25# Otherwise, create file.
26file = Path(dname + "/database.txt")
27if file.is_file():
28 print("File exists.\n")
29 print("Coping file.\n")
30 copyfile(str(file), str(dname + "\database_BACKUP.txt"))
31 with open("database.txt", "w"):
32 pass
33else:
34 print("File does not exist.\n")
35 print("Creating file.\n")
36 with open('database.txt', 'w+') as f:
37 for line in f:
38 print(line)
39 f.write("")
40 f.close()
41
42
43# Begin database interaction
44conn = sqlite3.connect()
45cur = conn.cursor()
46tables=["tablename1","tablename2","tablename3","tablename4"]
47for table in tables:
48 cur.execute("SELECT * FROM ?", table)
49 rows = cur.fetchall()
50 # Append database table contents to file
51 with open('database.txt', 'a') as f:
52 f.write(rows)
53 f.close()
54conn.commit()
55conn.close()