Python edit

Creating temporary files with tempfile

You can create temporary files which has a visible name on the file system which can be accessed via the name property. The file can, on unix systems, be configured to delete on closure (set by delete param, default is True) or can be reopened later.

The following will create and open a named temporary file and write ‘Hello World!’ to that file. The path of the temporary file can be accessed via name, in this example it is saved to the variable path and printed for the user. The file is then re-opened after closing the file and the contents of the tempfile are read and printed for the user.

import tempfile

with tempfile.NamedTemporaryFile(delete=False) as t:
	t.write(Hello World!’) 
	path = t.name
	print path
	with open(path) as t:
	    print t.read()

Output:

/tmp/tmp6pireJ
Hello World!

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Table Of Contents
32 Set
46 Enum
103 Creating temporary files with tempfile
105 Stack
119 Mixins
121 ArcPy
127 Arrays
139 Neo4j
141 Curses
146 heapq
155 Audio
156 pyglet
158 ijson
161 Flask
164 pygame
167 Gzip
168 ctypes
187 shelve
  ↑ ↓ to navigate     ↵ to select     Esc to close