Code Explanation:
1. Importing Modules
import os
from pathlib import Path
os → Provides functions for interacting with the operating system (like checking if files exist).
pathlib.Path → A modern way to handle filesystem paths as objects (instead of plain strings).
2. Creating a Path Object
p = Path("sample.txt")
Creates a Path object pointing to "sample.txt".
At this point, no file is created yet — it’s just a path representation.
3. Writing to the File
p.write_text("Hello")
Creates the file "sample.txt" (if it doesn’t exist).
Writes the string "Hello" into the file.
Returns the number of characters written (in this case, 5).
4. Checking File Existence & Size
print(os.path.isfile("sample.txt"), p.stat().st_size)
os.path.isfile("sample.txt") → Returns True if "sample.txt" exists and is a regular file.
p.stat().st_size → Gets metadata of the file (stat) and fetches its size in bytes.
"Hello" is 5 characters → size = 5 bytes.
Output will be:
True 5
5. Deleting the File
p.unlink()
Removes (deletes) the file "sample.txt".
After this line, the file no longer exists on disk.
Final Output
True 5


0 Comments:
Post a Comment