我是编程新手,并且正在使用Python编写一个函数来传输过去24小时内创建或修改的文件。我现在需要弄清楚如何使用SQlite3数据库来跟踪上次文件传输的时间和日期。我知道如何在SQlite3中创建数据库和表,但是在将它绑定到文件传输功能时却不知所措。这是我的文件传输代码:
import os,time
import datetime
import shutil
import datetime as dt
conn = sqlite3.connect('file_check.db')
c = conn.cursor()
now = dt.datetime.now()
ago = now-dt.timedelta(hours=24)
strftime = "%H:%M %m/%d/%Y"
created = ('C:\\Users\\Jacqueline\\Desktop\\created')
dest = ('C:\\Users\\Jacqueline\\Desktop\\dest')
def file_trans(created, dest):
for root, dirs,files in os.walk(created):
for fname in files:
path = os.path.join(root, fname)
st = os.stat(path)
mtime = dt.datetime.fromtimestamp(st.st_mtime)
if mtime > ago:
print("True: ", fname, " at ", mtime.strftime("%H:%M %m/%d/%Y"))
shutil.move(path, dest)
c.execute("INSERT INTO FileCheck (unix, datestamp, timestamp) VALUES (?,?,?)", (unix, datestamp, timestamp))
conn.commit
conn.close
def main(source, destination):
# parameters passed into file_trans
source = created
destination = dest
#call file_trans
file_trans(source, destination)
if __name__=='__main__':
main()
关于如何以某种方式将其链接到SQlite3表的任何想法,以便我可以跟踪文件传输何时发生?我创建数据库的代码是:
import sqlite3
import time
import datetime #creates datestamp
import random #creates value
conn = sqlite3.connect("file_check.db") #defines connection
c = conn.cursor()
def create_table():
c.execute("CREATE TABLE IF NOT EXISTS FileCheck(unix REAL, datestamp TEXT, timestamp TEXT)")
def dynamic_data_entry():
unix = time.time() #timestamp
datestamp = str(datetime.datetime.fromtimestamp(unix).strftime('%m/%d/%Y')) #formats datestamp
timestamp = str(datetime.datetime.fromtimestamp(unix).strftime('%H:%M:%S'))
c.execute("INSERT INTO FileCheck (unix, datestamp, timestamp) VALUES (?,?,?)",
(unix, datestamp, timestamp))
conn.commit()
create_table()
c.close()
conn.close()
表格很好 - 我只需要将它链接到函数。
答案 0 :(得分:0)
看起来您只需要定义要传递给execute语句的变量。如果您仍然遇到错误,请发布您正在使用的当前代码,以及您获得的完整堆栈跟踪(错误消息)。令人惊讶的是,有多少可以告诉人们出了什么问题。
我还将连接创建移动到了该功能中,因此在调用该功能之前,您不会遇到关闭连接的问题。
import os,time
import datetime
import shutil
import datetime as dt
import sqlite3
now = dt.datetime.now()
ago = now-dt.timedelta(hours=24)
strftime = "%H:%M %m/%d/%Y"
created = ('C:\\Users\\Jacqueline\\Desktop\\created')
dest = ('C:\\Users\\Jacqueline\\Desktop\\dest')
def file_trans(created, dest):
conn = sqlite3.connect('file_check.db')
c = conn.cursor()
for root, dirs,files in os.walk(created):
for fname in files:
path = os.path.join(root, fname)
st = os.stat(path)
mtime = dt.datetime.fromtimestamp(st.st_mtime)
if mtime > ago:
print("True: ", fname, " at ", mtime.strftime("%H:%M %m/%d/%Y"))
shutil.move(path, dest)
unix = time.time()
datestamp = str(datetime.datetime.fromtimestamp(unix).strftime('%m/%d/%Y'))
timestamp = str(datetime.datetime.fromtimestamp(unix).strftime('%H:%M:%S'))
c.execute("INSERT INTO FileCheck (unix, datestamp, timestamp) VALUES (?,?,?)", (unix, datestamp, timestamp))
conn.commit()
conn.close()