[英]Python tempfile module's temporary directory issues
So I have created the following function which takes an image the user chooses from the tkinter file browser, opens it, re-saves it as a .gif
(which is required ) in a temporary directory , and then sets it as the background of the tkinter canvas:所以我创建了以下函数,它获取用户从 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')
However, whenever the above code is run, I get the following error:但是,每当运行上述代码时,都会出现以下错误:
FileNotFoundError: [Errno 2] No such file or directory: 'var/folders/g_/099nlyhn51gf_sy21gvcp2fc0000gn/T/tmpj2z501ml/Users/Name/Pictures/ImageName.jpg.gif'
Apparently the directory cannot be found even though I created it with temple.mkdtemp()
.显然,即使我使用temple.mkdtemp()
创建了该目录,也无法找到该目录。 What am I doing wrong here that is causing this error?我在这里做错了什么导致了这个错误? Any help is greatly appreciated!任何帮助是极大的赞赏! :) :)
You appear to be trying to append the entire path to the file onto the temprary directory (so instead of /path/to/tmpdir/ImageName.jpg.gif
, you're using /path/to/tmpdir/Users/Name/Pictures/ImageName.jpg.gif
.您似乎试图将文件的整个路径附加到临时目录中(因此您使用的是/path/to/tmpdir/Users/Name/Pictures/ImageName.jpg.gif
而不是/path/to/tmpdir/ImageName.jpg.gif
/path/to/tmpdir/Users/Name/Pictures/ImageName.jpg.gif
。
You didn't specify on which line the error is happening, but I suspect you're getting an error when trying to save the file, because those intervening directories don't exist.您没有指定错误发生在哪一行,但我怀疑您在尝试保存文件时遇到错误,因为这些中间目录不存在。
Consider just taking the basename of the file:考虑只取文件的基本名称:
img.save(os.path.join(tmp, os.path.basename(cng) + '.gif'), 'GIF')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.