Code Explanation:
1. Importing Required Modules
import tempfile, os
tempfile → allows us to create temporary files and directories.
os → provides functions to interact with the operating system (like checking or deleting files).
2. Creating a Temporary File
with tempfile.NamedTemporaryFile(delete=False) as tmp:
NamedTemporaryFile() → creates a temporary file.
delete=False → means do not delete automatically when the file is closed.
as tmp → gives us a file object (tmp).
So now a temp file is created in your system’s temp folder.
3. Writing Data to Temporary File
tmp.write(b"Python Temp File")
.write() → writes data into the file.
b"Python Temp File" → a byte string (since file is opened in binary mode).
The temporary file now contains "Python Temp File".
4. Saving the File Name
name = tmp.name
tmp.name → gives the full path of the temporary file.
This path is stored in name so we can use it later.
5. Checking File Existence
print(os.path.exists(name))
os.path.exists(name) → checks if the file at path name exists.
At this point → the file does exist.
Output: True
6. Removing the File
os.remove(name)
os.remove(path) → deletes the file at the given path.
Now the temp file is deleted from disk.
7. Checking Again After Deletion
print(os.path.exists(name))
Again checks if the file exists.
Since we deleted it, the result is False.
Final Output
True
False


0 Comments:
Post a Comment