Back
+15 XP
Concept

Temporary Files and Directories with tempfile

`tempfile.NamedTemporaryFile` creates collision-free temporary files that automatically delete themselves when closed, eliminating disk leaks 📁.

python
import tempfile

with tempfile.NamedTemporaryFile(mode="w+", delete=True) as tmp:
    tmp.write("Sensitive cache data")
    tmp.seek(0)
    print(f"Read from {tmp.name}: {tmp.read()} 📁")

print("Temp file securely deleted! 🗑️")

# 108. Temporary Files and Directories with tempfile `tempfile.NamedTemporaryFile` creates collision-free temporary files that automatically delete themselves when closed, eliminating disk leaks 📁. ```python import tempfile with tempfile.NamedTemporaryFile(mode="w+", delete=True) as tmp: tmp.write("Sensitive cache data") tmp.seek(0) print(f"Read from {tmp.name}: {tmp.read()} 📁") print("Temp file securely deleted! 🗑️") ``` Using `tempfile` avoids race conditions where two simultaneous process runs overwrite the same hardcoded `/tmp/temp.txt` file! 📁 --- ### Question Why should you use `tempfile.NamedTemporaryFile` instead of writing to a hardcoded path like `/tmp/data.txt`? 🧠 - [ ] a. Generates collision-free names securely and guarantees cleanup on close 📁 - [ ] b. Bypasses disk writes by storing files in GPU cache - [ ] c. Encrypts files with RSA-4096 by default - [ ] d. Allows multiple root users to edit the file simultaneously --- ### Challenge Import `tempfile`. Use `with tempfile.NamedTemporaryFile('w+', delete=True) as tf:` write `'AUTO_CLEAN'`, seek to 0, read and print the contents. 🎯 <details> <summary>Solution</summary> ```python import tempfile with tempfile.NamedTemporaryFile("w+", delete=True) as tf: tf.write("AUTO_CLEAN") tf.seek(0) print(tf.read()) ``` </details>

Checkpoint

Why should you use `tempfile.NamedTemporaryFile` instead of writing to a hardcoded path like `/tmp/data.txt`? 🧠

Practice

Import `tempfile`. Use `with tempfile.NamedTemporaryFile('w+', delete=True) as tf:` write `'AUTO_CLEAN'`, seek to 0, read and print the contents. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks