with open("example.txt", "r") as file:
content = file.read()
print("File Contents:")
print(content)
#source code --> clcoding.com
Code explanation:
Opening the File:
We use open("example.txt", "r") to open the file in read mode ("r").
The "r" mode ensures that we are only reading the file, not modifying it.
If the file does not exist, Python will raise a FileNotFoundError.
Using with Statement:
The with open(...) as file: statement ensures the file is closed automatically after the block is executed.
Reading the File:
The read() function reads all the content from the file and stores it in the variable content.
Printing the Contents:
print(content) displays the contents of the file on the screen.
0 Comments:
Post a Comment