6.1 Opening and Closing Files
We learn the basic open() function, its various modes, and the importance of the close() method for file management.
To work with a file on disk, the first step is to open it. The built-in `open()` function is the key to this process. It returns a "file object," which is like an intermediary that allows you to read or write data to the physical file.
The open() Function
The `open()` function takes two main arguments: the file path and the mode in which to open it. It is crucial to always close the file with the `close()` method to release system resources and ensure any changes are properly saved to disk.
File Modes
- `"r"` (Read): Default mode. Opens a file for reading. Raises an error if the file does not exist.
- `"w"` (Write): Opens a file for writing. If the file exists, its content is deleted. If it does not exist, a new one is created.
- `"a"` (Append): Opens a file for appending to the end. If it does not exist, a new one is created.
- `"x"` (Create): Creates a new file. If the file already exists, it raises an error.
You can also add a `"+"` (e.g., `"r+"`, `"w+"`) to allow simultaneous reading and writing.
Tip!
The live editor operates in a temporary environment. The files you create are not permanently stored, but the code is fully functional in a normal Python environment.
# Example of writing, reading, and appending to a file.
# Note: This file is temporary in the live editor.
# 1. Writing to a file (mode "w" - replaces content)
try:
file_writer = open("my_first_file.txt", "w", encoding="utf-8")
file_writer.write("This is my first line in a file.\n")
file_writer.close()
print("'my_first_file.txt' was created for writing.")
except Exception as e:
print(f"Write error: {e}")
# 2. Reading from a file (mode "r")
try:
file_reader = open("my_first_file.txt", "r", encoding="utf-8")
content = file_reader.read()
print("\nContent of 'my_first_file.txt':\n" + content)
file_reader.close()
except FileNotFoundError:
print("\nError: 'my_first_file.txt' not found.")
# 3. Appending to a file (mode "a")
try:
file_appender = open("my_first_file.txt", "a", encoding="utf-8")
file_appender.write("This line was appended to the end.\n")
file_appender.close()
print("A new line was appended to the file.")
except Exception as e:
print(f"Append error: {e}")
# 4. Reading again to confirm
try:
file_final_reader = open("my_first_file.txt", "r", encoding="utf-8")
print("\nFinal content of 'my_first_file.txt':")
for line in file_final_reader:
print(line.strip())
file_final_reader.close()
except FileNotFoundError:
print("Error: 'my_first_file.txt' not found for final read.")
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.