[英]Python tempfile module's temporary directory issues
所以我創建了以下函數,它獲取用戶從 tkinter 文件瀏覽器中選擇的圖像,打開它,將其重新保存為.gif
(這是必需的)在臨時目錄中,然后將其設置為背景tkinter 畫布:
def background():
# Create temporary directory and return path as 'tmp'
tmp = tempfile.mkdtemp()
# Ask user for image file
cng = filedialog.askopenfilename()
# Open the image using the PIL's `open` function
img = Image.open(cng)
# Supposed to save image to the `tmp` directory as a GIF
img.save(tmp + cng + '.gif', 'GIF')
# Supposed to set image file from temporary directory as background picture
bgpic(tmp + cng + '.gif')
但是,每當運行上述代碼時,都會出現以下錯誤:
FileNotFoundError: [Errno 2] No such file or directory: 'var/folders/g_/099nlyhn51gf_sy21gvcp2fc0000gn/T/tmpj2z501ml/Users/Name/Pictures/ImageName.jpg.gif'
顯然,即使我使用temple.mkdtemp()
創建了該目錄,也無法找到該目錄。 我在這里做錯了什么導致了這個錯誤? 任何幫助是極大的贊賞! :)
您似乎試圖將文件的整個路徑附加到臨時目錄中(因此您使用的是/path/to/tmpdir/Users/Name/Pictures/ImageName.jpg.gif
而不是/path/to/tmpdir/ImageName.jpg.gif
/path/to/tmpdir/Users/Name/Pictures/ImageName.jpg.gif
。
您沒有指定錯誤發生在哪一行,但我懷疑您在嘗試保存文件時遇到錯誤,因為這些中間目錄不存在。
考慮只取文件的基本名稱:
img.save(os.path.join(tmp, os.path.basename(cng) + '.gif'), 'GIF')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.