I am attempting to use the ‘tempfile’ module for manipulating and creating text files. Once the file is ready I want to save it to disk. I thought it would be as simple as using ‘shutil.copy’. However, I get a ‘permission denied’ IOError:
>>> import tempfile, shutil >>> f = tempfile.TemporaryFile(mode ='w+t') >>> f.write('foo') >>> shutil.copy(f.name, 'bar.txt') Traceback (most recent call last): File '<pyshell#5>', line 1, in <module> shutil.copy(f.name, 'bar.txt') File 'C:\Python25\lib\shutil.py', line 80, in copy copyfile(src, dst) File 'C:\Python25\lib\shutil.py', line 46, in copyfile fsrc = open(src, 'rb') IOError: [Errno 13] Permission denied: 'c:\\docume~1\\me\\locals~1\\temp\\tmpvqq3go' >>>
Is this not intended when using the ‘tempfile’ library? Is there a better way to do this? (Maybe I am overlooking something very trivial)
The file you create with
TemporaryFileorNamedTemporaryFileis automatically removed when it’s closed, which is why you get an error. If you don’t want this, you can usemkstempinstead (see the docs for tempfile).