file = open("myfile.txt", "r")
lines = file.readlines()
print(lines) # List of linesfile.close()
✍️ Writing Files
Write (overwrites):
file = open("output.txt", "w")
file.write("Hello, World!\n")
file.write("This is line 2.\n")
file.close()
Append (add to end):
file = open("output.txt", "a")
file.write("This is added later.\n")
file.close()
✅ The "with" Statement
Always use with - it automatically closes the file even if errors occur:
# BEST PRACTICE - Always use this!withopen("myfile.txt", "r") asfile:
content = file.read()
print(content)
# File automatically closed here!
💡 Why use "with"? If your code has an error before calling close(), the file might not be saved properly. The "with" statement guarantees the file is closed.