在 Python 中删除文件时出现错误“进程无法访问文件”

S A*_*rew 0 python delete-file

我正在开发一个项目,其中目录中存储了许多 json 文件。我需要读取所有文件并检查其中的数据。is如果任何文件中存在“会话错误”,我需要删除该文件。下面是代码:

files = os.listdir(config_files_path)
for file in files:
    file_path = config_files_path + '//' + file
    f = open(file_path)

    data = json.load(f)

    if not data['session']:
        # delete this file
        os.remove(file_path)
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我获取了所有文件的列表。然后迭代每个文件并读取其内容dataif not data['session'],我需要删除该文件。但这样做我得到了process cannot access the file as its being used by another process。有什么办法可以删除该文件。请帮忙。谢谢

aja*_*dhi 5

您需要在删除文件之前关闭该文件。在 os.remove(file_path) 语句之前使用 f.close()