我正在尝试使用 Python 使用目录中的文件名列表填充 sqlite3 数据库。我不确定为什么这不起作用:
conn = sqlite3.connect( "databasefile.db" )
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS filenames (filename TEXT)')
for root, dirnames, filenames in os.walk(directory):
for filename in filenames:
if filename.endswith(".ext"):
cur.executemany('INSERT INTO filenames (filename) VALUES (?)', (filename))
conn.commit()
我希望它在数据库文件中生成这个:
Column
1 1st.ext
2 2nd.ext
3 3rd.ext
但结果却是这样的:
Column
1 1
2 r
3 s
4 t
5 .
6 e
7 x
8 t
9 2
10 n
11 d
12 .
etc.
任何人都可以帮助我了解哪里出了问题吗?
编辑: 谢谢,我没有意识到遍历字符串会给出单个字符。添加逗号使“文件名”成为元组并解析。
最佳答案
首先,您不需要使用 executemany,因为您实际上并没有一次执行多个插入操作。其次,将 (filename)
更改为 (filename,)
。字符串和元组都支持迭代器协议(protocol),如果没有逗号,executemany 函数会将变量 filename
解释为要迭代的对象。当您遍历一个字符串时,您会得到单独的字符。
您可能会做的另一件事如下:
for root, dirnames, filenames in os.walk(directory):
cur.executemany("INSERT INTO filenames (filename) VALUES (?)",
[(filename,) for filename in filenames if filename.endswith(".ext")])
conn.commit()
现在您实际上是在利用 executemany,而且一般来说,越少访问数据库越好。
关于python - 使用 Python 的 sqlite 文件名列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13334507/