Python tempfile模块的临时目录问题

时间:2016-02-07 04:07:18

标签: python temporary-files python-3.5

所以我创建了以下函数,该函数接收用户从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()创建了目录,也无法找到目录。我在这里做错了导致此错误的内容?非常感谢任何帮助! :)

1 个答案:

答案 0 :(得分:0)

您似乎试图将文件的整个路径附加到temprary目录(因此,name="{{bindThisValuePerAnswerOption}}" 代替/path/to/tmpdir/ImageName.jpg.gif,而不是/path/to/tmpdir/Users/Name/Pictures/ImageName.jpg.gif

您没有指定错误发生在哪一行,但我怀疑您在尝试保存文件时遇到错误,因为这些干预目录不在存在。

考虑只获取文件的基本名称:

img.save(os.path.join(tmp, os.path.nasename(cng) + '.gif'), 'GIF')