Skip to content

Instantly share code, notes, and snippets.

@lkluft
Last active June 29, 2016 09:35
Show Gist options
  • Save lkluft/4c2819bf47460f1dda69ceaabd99562f to your computer and use it in GitHub Desktop.
Save lkluft/4c2819bf47460f1dda69ceaabd99562f to your computer and use it in GitHub Desktop.
Create and use a temporary file.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"metadata": {
"collapsed": false,
"ExecuteTime": {
"start_time": "2016-06-29T11:35:15.921864",
"end_time": "2016-06-29T11:35:15.930885"
},
"trusted": true
},
"cell_type": "code",
"source": "import os\nfrom tempfile import NamedTemporaryFile\n\n\n# Dictionary containing all parameters to be passed to NamedTemporaryFile.\nkwargs = {'prefix': 'test-',\n 'suffix': '.txt',\n 'dir': '/dev/shm/u300509/',\n }\n\n# Use the with statement to open a temporary file the clean way.\nwith NamedTemporaryFile(**kwargs) as t:\n t.write(b'Test sentence.') # Write to tempfile\n print(os.listdir(kwargs['dir']))\n\n# The file is deleted when the block is completed or the script is interrupted.\nprint(os.listdir(kwargs['dir']))",
"execution_count": 1,
"outputs": [
{
"output_type": "stream",
"text": "['test-tohb1_w7.txt']\n[]\n",
"name": "stdout"
}
]
}
],
"metadata": {
"kernelspec": {
"name": "python3",
"display_name": "Python 3",
"language": "python"
},
"gist": {
"id": "4c2819bf47460f1dda69ceaabd99562f",
"data": {
"description": "Create and use a temporary file.",
"public": true
}
},
"language_info": {
"nbconvert_exporter": "python",
"version": "3.5.1",
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"name": "python",
"mimetype": "text/x-python",
"file_extension": ".py",
"pygments_lexer": "ipython3"
},
"toc": {
"toc_threshold": 6,
"toc_window_display": false,
"toc_number_sections": true,
"toc_cell": false
},
"_draft": {
"nbviewer_url": "https://gist.github.com/4c2819bf47460f1dda69ceaabd99562f"
},
"widgets": {
"state": {},
"version": "1.1.2"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment