Section Overview
In this section, you’ll learn how to work with files in Python. Reading from and writing to files allows your programs to save data permanently, share information, and interact with the outside world.
By the end of this section, you should be able to:
- Open files for reading and writing
- Read contents of a file
- Write data to a file
- Properly close files or use context managers
Lesson 1: Opening and Closing Files
You open a file using the open()
function, specifying the filename and mode ('r'
for reading, 'w'
for writing).
Example:
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
Closing the file with file.close()
is important to free resources.
Lesson 2: Using with
Statement (Context Manager)
A better practice is to use with
which automatically closes the file:
with open("example.txt", "r") as file:
content = file.read()
print(content)
Lesson 3: Writing to Files
To write, open the file in write mode ('w'
). This overwrites the file if it exists or creates a new one.
Example:
with open("output.txt", "w") as file:
file.write("Hello, file!\n")
You can use write()
multiple times to add more content.
Lesson 4: Reading Files Line by Line
You can read files line by line using a loop:
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
strip()
removes the newline character at the end of each line.
Quiz: Check Your Understanding
1. What mode do you use to open a file for writing?
Answer: 'w'
2. What does the with
statement do when working with files?
Answer: It automatically closes the file when done.
3. How can you read a file line by line?
Answer: By looping through the file object with a for
loop.
4. What happens if you open a file in write mode ('w'
) and the file already exists?
Answer: The file is overwritten (its previous content is erased).
Practice Exercise: Logging User Input
Write a program that:
- Asks the user to enter text repeatedly
- Writes each entered line to a file called
log.txt
- Stops asking when the user types
"exit"
Starter code:
with open("log.txt", "w") as file:
while True:
line = input("Enter text (type 'exit' to stop): ")
if line.lower() == "exit":
break
file.write(line + "\n")