【问题标题】:Unable to delete .db file from within my script, but can do so from anywhere else无法从我的脚本中删除 .db 文件,但可以从其他任何地方删除
【发布时间】:2019-06-06 08:04:35
【问题描述】:

如果我运行下面的脚本,它会抛出显示的错误。但是,如果我切换终端并运行相同的命令来删除文件 (os.remove("test.db")),则会删除该文件。

import gc
import os
import time

from sqlite3 import connect
from contextlib import contextmanager


file = "test.db"


@contextmanager
def temptable(cur: object):
    cur.execute("create table points(x, int, y int)")
    try:
        yield
    finally:
        cur.execute("drop table points")


with connect(file) as conn:
    cur = conn.cursor()
    with temptable(cur=cur):
        cur.execute("insert into points (x, y) values(1, 1)")
        cur.execute("insert into points (x, y) values(1, 2)")
        cur.execute("insert into points (x, y) values(2, 1)")
        for row in cur.execute("select x, y from points"):
            print(row)
        for row in cur.execute("select sum(x * y) from points"):
            print(row)

os.remove(file)

文件“c:\Users\You_A\Desktop\2019Coding\context_generator_decorator.py”,第 32 行,在 os.remove(文件) PermissionError: [WinError 32] 进程无法访问该文件,因为它正被另一个进程使用:'test.db'

同样,在任何终端中运行 os.remove("test.db") 会成功删除文件。

【问题讨论】:

  • 您已经在使用该文件
  • 你在过程中哪里提到了os.remove("test.db")的使用?
  • 我不知道你的意图,但如果它是关于暂时使用 SQLite3 而不将任何结果保存到文件中,你可以使用 :memory: 而不是文件名。另外,如果要删除整个文件,为什么要DROP TABLE?另外,一个INSERT 就足够了:cur.execute("insert into points (x, y) values(1, 1),(1, 2),(2, 1)")
  • @tonypdmtr 只是想弄清楚上下文管理器、装饰器和生成器

标签: python sqlite


【解决方案1】:

这可能是由于与数据库的连接没有关闭造成的。尝试使用contextlib.closing()。修改后的代码看起来像,

import gc
import os
import time

from sqlite3 import connect
from contextlib import contextmanager, closing


file = "test.db"


@contextmanager
def temptable(cur: object):
    cur.execute("create table points(x, int, y int)")
    try:
        yield
    finally:
        cur.execute("drop table points")


with closing(connect(file)) as conn:
    # cur = closing(conn.cursor()) --> if auto-closing of cursor is desired
    cur = conn.cursor() # if auto closing of cursor is not desired
    with temptable(cur=cur):
        cur.execute("insert into points (x, y) values(1, 1)")
        cur.execute("insert into points (x, y) values(1, 2)")
        cur.execute("insert into points (x, y) values(2, 1)")
        for row in cur.execute("select x, y from points"):
            print(row)
        for row in cur.execute("select sum(x * y) from points"):
            print(row)

os.remove(file)

【讨论】:

  • 你能改变 cur = closing(conn.cursor()) --> cur = conn.cursor() 以便我可以接受它作为答案吗?没有那个代码很好。
  • 前一条语句的问题是:AttributeError: 'closing' object has no attribute 'execute'
猜你喜欢
  • 2022-10-13
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
  • 2012-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多