Creating temporary files with tempfile:
Creating temporary files with tempfile
suggest changeYou 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!
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents
3List
22Reduce
27Classes
28Counting
31Set
42Tuple
45Enum
60setup.py
62Sockets
89urllib
92Idioms
102Creating temporary files with tempfile
104Stack
105Profiling
109Logging
111os module
118Mixins
120ArcPy
123Websockets
126Arrays
128Polymorphism
1322to3 tool
135Unicode
138Neo4j
140Curses
141Templates
145heapq
146tkinter
154Audio
155pyglet
156queue module
157ijson
160Flask
161Groupby
163pygame
165hashlib
166Gzip
167ctypes
170configparser
179sys module
185pyaudio
186shelve
191Contributors