Created
June 17, 2020 13:50
-
-
Save strboul/272eeeedc16bb50e511f40adf18c919e to your computer and use it in GitHub Desktop.
Write to a tempfile by 'tempfile' module (in Python 3.7)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tempfile | |
def write_to_temp_file(obj): | |
""" | |
Write an object to a temporary file. The location of the temp file is | |
determined by the OS. | |
Args: | |
obj: a writable object. | |
Returns: | |
str: the temp file path. | |
""" | |
temp_name = None | |
with tempfile.NamedTemporaryFile(delete=False) as temp: | |
temp.write(bytes(obj, encoding='utf-8')) | |
temp_name = temp.name | |
assert temp_name is not None | |
return temp_name | |
# Simple string ------------------------ | |
x=write_to_temp_file('hello') | |
print(x) | |
open(x,'r',encoding = 'utf-8').read() | |
# JSON ------------------------ | |
import json | |
js=json.dumps({'lat': 0, 'lon': 0}) | |
y=write_to_temp_file(js) | |
print(y) | |
open(y,'r',encoding = 'utf-8').read() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment