【问题标题】:Problem with writing a file on a certain path在特定路径上写入文件的问题
【发布时间】:2020-07-29 08:31:51
【问题描述】:

我尝试通过指定要保存的文件夹的路径将文件写入磁盘。但是我得到了通过指定路径读取文件的错误。

FileNotFoundError: [Errno 2] No such file or directory: '/home/jekson/Projects/img-text-reco/static/product_images/24f2a9d0372a49bc8c5eb259798477f0.jpeg'

此行出现错误。

async with aiofiles.open(os.path.join(IMG_DIR, file_name)) as f

为了清楚起见,我进行了打印调用,指示了正文函数中的路径

from db import BASEDIR

print(BASEDIR) # /home/jekson/Projects/img-text-reco

def file_upload():
    ....
    IMG_DIR = os.path.join(BASEDIR, 'static/product_images')
    if not os.path.exists(IMG_DIR):
        os.makedirs(IMG_DIR)
    print(f'IMG_DIR {IMG_DIR}') # IMG_DIR /home/jekson/Projects/img-text-reco/static/product_images
    content = await file.read()
    if file.content_type not in ['image/jpeg', 'image/png']:
        raise HTTPException(status_code=406, detail="Only .jpeg or .png  files allowed")
    file_name = f'{uuid.uuid4().hex}{ext}'
    print(os.path.join(IMG_DIR, file_name)) # /home/jekson/Projects/img-text-reco/static/product_images/24f2a9d0372a49bc8c5eb259798477f0.jpeg
    async with aiofiles.open(os.path.join(IMG_DIR, file_name)) as f:
        await f.write(content)
    path_to_img = os.path.abspath(os.path.join(IMG_DIR, file_name))
    ....

【问题讨论】:

    标签: python python-3.x python-os python-aiofiles


    【解决方案1】:

    您打开文件进行阅读,但它不存在,因此出现错误。以下f.write 建议您改为打开文件进行写入:

    async with aiofiles.open(os.path.join(IMG_DIR, file_name), mode='w') as f:
    

    【讨论】:

    • 没错。没听懂。谢谢!就我而言,我将不得不使用 wb 而不是 w
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    相关资源
    最近更新 更多