2.9.1.5 Opening, Reading, and Closing Files
Python Programming
To read a file, open it using the open() function, read its contents, and then close the file to free up resources.
python
# Open and read a file
with open("example.txt", "r") as file:
content = file.read ()
print(content)Explanation: In the above code:
- The with statement ensures that the file is properly closed after its suite finishes, even if an error occurs.
- The file is opened in read mode (r), read contents into content, and then printed.
- The file opened using 'with' is automatically closed.