【问题标题】:Python: The process cannot access the file because it is being used by another process:Python:该进程无法访问该文件,因为它正在被另一个进程使用:
【发布时间】:2021-07-23 11:05:36
【问题描述】:

我有后端代码,它应该下载 instagram 个人资料图片并将其发送到前端,然后它应该删除存储该图片的文件夹。它在将图像发送到前端时有效,但完成后不会删除文件夹。图片下载时的文件夹结构:

用户名(要删除的文件夹)

  1. 个人资料图片.jpg
  2. 用户名.date.json.xz
  3. 身份证

错误提示删除文件有问题,因为 profile-picture.jpg 已被另一个进程使用

import os
import shutil
from flask import Flask, request, send_file
import instaloader

app = Flask(__name__)

@app.route('/get-profile-picture')
def get_profile_picture():
    try:
        username = request.args.get('username')
        mod = instaloader.Instaloader()
        mod.download_profile(username, profile_pic_only=True)
        print("before send")
        return send_file(f'{username}/' + os.listdir(f'{username}')[0])
    except instaloader.exceptions.ProfileNotExistsException:
        return "Profile doesn't exist"
    finally:
        delete_folder(username)
        

def delete_folder(folder_name):
    if os.path.isdir(folder_name):
        shutil.rmtree(folder_name)

【问题讨论】:

    标签: python flask instagram-api


    【解决方案1】:

    在图像下载功能中将文件保存到内存后是否关闭?当您打开它以将其发送到前端时也是如此。完成所需的处理后,您可以使用 with 或手动关闭文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-10
      相关资源
      最近更新 更多