What You Will Learn
Beginner
- How to open, read, and write files
- The with statement (context manager)
- File modes (r, w, a, r+)
Terminalpython
# Writing to a file
with open("output.txt", "w") as f:
f.write("Hello, World!\n")
f.write("Second line.\n")
# Reading from a file
with open("output.txt", "r") as f:
content = f.read() # Read entire file
print(content)
# Read line by line
with open("output.txt", "r") as f:
for line in f:
print(line.strip()) # strip() removes newline
# Append to a file
with open("output.txt", "a") as f:
f.write("Third line.\n")Always use with open()
The with statement automatically closes the file when done, even if an error occurs. Never use bare open() without with.Practical Exercise
Write 3 lines to a file with with open('test.txt', 'w')
Read it back with with open('test.txt', 'r')
Append a 4th line with mode 'a'
Read line by line with for line in f
Use .readlines() to get all lines as a list
Key Takeaways
- with open(path, mode) as f: - always use this pattern.
- Modes: r (read), w (write, overwrites), a (append).
- f.read() = entire file. f.readline() = one line.
- for line in f: iterates line by line.
- with auto-closes the file. Never use bare open().
Comments
Comments
Post a Comment