Code Explanation:
1. Importing Modules
os → gives functions for interacting with the operating system (like checking files).
Path (from pathlib) → an object-oriented way to handle filesystem paths.
p = Path("example.txt")
2. Creating a Path Object
Path("example.txt") creates a Path object pointing to a file named example.txt in the current working directory.
p now represents this file’s path.
with open(p, "w") as f:
f.write("hello")
3. Creating and Writing to File
open(p, "w") → opens the file example.txt for writing (creates it if it doesn’t exist, overwrites if it does).
f.write("hello") → writes the text "hello" into the file.
The with statement automatically closes the file after writing.
print(os.path.exists("example.txt"))
4. Checking File Existence (os.path)
os.path.exists("example.txt") → returns True if the file exists.
Since we just created and wrote "hello", this will print:
True
p.unlink()
5. Deleting the File
p.unlink() removes the file represented by Path("example.txt").
After this, the file no longer exists on the filesystem.
print(p.exists())
6. Checking File Existence (Pathlib)
p.exists() checks if the file still exists.
Since we just deleted it, this will print:
False
Final Output
True
False


0 Comments:
Post a Comment