首页 > 解决方案 > bottle.py 用 file.save() 提高 ValueError('I/O operation on closed file',)

问题描述

对于我目前的项目,我正在使用 python 瓶。目前,我正在尝试保存用户在表单中上传的文件,但它会引发上面显示的错误。我尽我所能遵循文档,但无论我尝试了什么,它都会出现这个错误。

这是功能:

def uploadFile(file, isPublic, userId, cu, dirId=-1):
    """Takes a bottle FileUpload instance as an argument and adds it to storage/media as well as adds its 
    info to the database. cu should be the db cursor. isPublic should be a bool. userId should be the 
    uploaders id. dirId is the directory ID and defaults to -1."""
    fakeName = file.filename
    extension = os.path.splitext(file.filename)[1]
    cu.execute("SELECT * FROM files WHERE fileId=(SELECT MAX(fileId) FROM files)")
    newId = cu.fetchone()
    if newId==None:
        newId = 0
    else:
        newId = newId[1]
    if debugMode:
        print(f"newId {newId}") 
    fileName = f"userfile-{newId}-{userId}.{extension}"
    file.save(vdata["m_folder"] + "/" + fileName)
    cu.execute("INSERT INTO files VALUES (?, ?, ?, ?, ?, ?)",
    (userId, newId, dirId, fakeName, fileName, isPublic))
    cu.connection.commit()

有谁知道问题可能是什么?

标签: pythonpython-3.xbottle

解决方案


看起来您还没有打开要写入的文件。你可以这样做:

with open('path/to/file', 'w') as file:
    file.write('whatever')

推荐阅读