[英]Why I can't read anything with File.open in python when I open the file to write first?
[英]Azure Function Python - No such file or directory when using file.open
我正在使用 Azure Function 使用 HTTP GET 請求檢索 a.xlsx 文件並將其上傳到 blob 存儲。 在代碼中,我使用 file.open 將內容寫入臨時文件,然后將文件上傳到 blob 存儲。
這是我正在使用的代碼。
fileData = open(pathlib.Path(__file__).parent / fileString, 'w+').write(r.content)
但它失敗了,Application Insights 響應說:
Exception: FileNotFoundError: [Errno 2] No such file or directory:
以下兩條路徑在我這邊的 singleton 模式下運行良好:
1、
import logging
from pathlib import Path
import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
path = str(Path.home()) + "/test.txt"
fileData = open(path, 'w+').write("testsomething")
return func.HttpResponse(
"create file with no problem."+path,
status_code=200
)
2、
import logging
import tempfile
import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
path = tempfile.gettempdir() + "/test.txt"
fileData = open(path, 'w+').write("testsomething")
return func.HttpResponse(
"create file with no problem."+path,
status_code=200
)
這篇文章說, 寫入臨時目錄的文件不能保證在調用中持續存在(也許你的問題是相似的,但不確定)。
您的代碼似乎與多實例無關,但無論如何,這不是推薦的方法。 正如 user3732793 在他的回答中所說,您可以直接將數據發送到存儲 blob 而無需臨時文件。 只需使用 HTTP GET 請求檢索 a.xlsx 文件,然后通過blob output 綁定或blob 存儲 sdk將數據發送到 blob 存儲。
我使用 tempfile 來解決這個問題。
fp = tempfile.NamedTemporaryFile()
fp.write(r.content)
然后,當上傳到 blob 存儲時,我必須打開文件並讀取字節。
with open(fp.name, 'rb') as data:
logging.info(data)
if azureConnector.exists():
logging.info('connector exists')
return
azureConnector.upload_blob(data, overwrite=True)
現在正在將文件上傳到 Azure blob 存儲。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.