Python tempfile模块的临时目录问题。

问题描述 投票:0回答:1

因此,我创建了以下函数,它将用户从 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().我在这里做错了什么,导致这个错误? 任何帮助都是非常感激的! :)

python temporary-files python-3.5
1个回答
0
投票

你似乎是想把文件的整个路径附加到临时目录上(所以不是把它附加到 /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')
© www.soinside.com 2019 - 2024. All rights reserved.