builtins.permissionerror,但没有文件?

时间:2014-03-31 18:06:06

标签: python python-3.x file-io in-place

我正在尝试使用fileinput模块对文件进行原位编辑,但它似乎不想工作。

我正在使用的代码:

for line in fileinput.FileInput(complaint_db, inplace=True, backup=(complaint_db + ".backup")):
            print("Started replacement")
            if line == myline:
                pass
            else:
                print(line)

备份参数已修改,因为我认为它可能会修复错误,但事实并非如此。在运行此命令之前文件不存在(我已经检查了一百次),之后也没有。我正在我的主目录中创建文件,所以不应该有错误。

以下是完整错误:

builtins.PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'c:\\Users\\Cody\\Documents\\ComplaintManagement\\complaints.dbc:\\Users\\Cody\\Documents\\ComplaintManagement\\complaints.db.backup'

我想另一个问题是,如何检查原始投诉.db是否在文件中某处打开,而不知道它可能在哪里打开。如果是这样,我可以从代码中的任何一点随意关闭它吗?

我无法执行f.close,因为在代码中此时不会定义f。我试过os.close(complaints_db)(complaint_db是一个保存数据库位置的通用变量)。它不起作用,因为它需要一个int,所以我现在有点迷失了。

1 个答案:

答案 0 :(得分:1)

我通过使用不同形式的更改数据库来修复此问题。而不是fileinput,我将其更改为以下代码:

from shutil import move
def RemoveClaim(self, myline):
     ocdb = open(complaint_db, 'r')
     ncdb = open(complaint_db + "2", 'w')
     for line in ocdb:
         if line == myline:
             pass
         else:
             ncdb.write(line)
     ocdb.close()
     ncdb.close()
     move(complaint_db + "2", complaint_db)

这似乎解决了我的问题,因为它有效,而且我没有错误。