我是python中的新手,我正在尝试将这些文件夹中的文件夹名称和文本文件添加到数据库中。问题是我不知道如何将“textfiles”和“opendirectory”添加到数据库中。请查看此代码并帮助我。感谢
#!/usr/bin/python
from easygui import *
import sys, glob, os, sqlite3
msgbox("Please choose your folder ","Welcome to MTT", ok_button ="Choose")
opendirectory = diropenbox("Welcome", "MTT",None)
con = sqlite3.connect('test.db')
cur = con.cursor()
cur.execute('DROP TABLE IF EXISTS folder')
cur.execute('DROP TABLE IF EXISTS file')
cur.execute('CREATE TABLE folder( folderid INTEGER PRIMARY KEY, foldername VARCHAR(120))')
cur.execute('CREATE TABLE file( fileid INTEGER PRIMARY KEY, folderid INTEGER, dataname VARCHAR(120), FOREIGN KEY(folderid) REFERENCES foldername(folderid))')
con.commit()
def main():
for dirpath,dirnames,filenames in os.walk(opendirectory):
for textfiles in filenames:
print textfiles
print opendirectory
cur.execute ('INSERT INTO folder (folderid, foldername) VALUES (null,opendirector)')
cur.execute('INSERT INTO file(fileid, dataname) VALUES(null,textfiles)')
cur.execute('SELECT * FROM folder')
print cur.fetchall()
main()
print 'success'
答案 0 :(得分:2)
假设您要将所有文件名添加到数据库中(不考虑opendirectory
中的相对路径),这是一种纠正查询的方法。
cur.execute ("INSERT INTO folder (foldername) VALUES (?);", (opendirectory))
cur.execute("INSERT INTO file (dataname) VALUES(?);", (textfiles))
注意:这不足以在数据库中创建文件与找到它的opendirectory
之间的逻辑链接。
现在,假设您希望在文件的DB 路径中存储文件以及文件名:
只需在parent_folder
表中添加一列file
,然后使用这样的插入查询(我更改了变量名称以便于理解):
for dirpath, dirsInDirpath, filesInDirPath in os.walk(opendirectory):
for myfile in filesInDirPath:
cur.execute("INSERT INTO file (dataname, parent_folder) VALUES(?, ?);", (myfile, dirpath))