无法从我的脚本中删除.db文件,但可以从其他任何地方删除

时间:2019-06-06 08:04:35

标签: python sqlite

如果我运行以下脚本,它将引发显示的错误。但是,如果我切换终端并运行相同的命令来删除文件( <div class="menu__style"> <input type="radio" name="colorize" value="Default" onclick="color_picker.unsetAlternateStyleSheet()" class="menu__style__item" id="style-default"> <label for="style-default" class="menu__style__label">Default Style</label> <br> <input type="radio" name="colorize" value="AlternateStyleOne" onclick="color_picker.setAlternateStyleSheet(title = this.value)" class="menu__style__item" id="style-one"> <label for="style-one" class="menu__style__label">First Alternative Style</label> <br> <input type="radio" name="colorize" value="AlternateStyleTwo" onclick="color_picker.setAlternateStyleSheet(title = this.value)" class="menu__style__item" id="style-two"> <label for="style-two" class="menu__style__label">Second Alternative Style</label> </div> ),则文件将被删除。

os.remove("test.db")
  
    
      

文件“ c:\ Users \ You_A \ Desktop \ 2019Coding \ context_generator_decorator.py”,第32行,在           os.remove(文件)       PermissionError:[WinError 32]该进程无法访问文件,因为该文件正在被另一个进程使用:'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) 都会成功删除文件。

1 个答案:

答案 0 :(得分: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)