Basic File Reading and Writing Operations in Python
- Opening and Closing Files
Before interacting with a file, you must first initialize a file handle using Python's built-in open() function. The standard function signature for common use cases is:
def open(
target_path: str | int,
access_mode: str = "r",
buffer_policy: int = -1,
text_encoding: str | None = None,
error_strategy: str | None = None,
newline_handler: str | None = None,
close_fd: bool = True,
custom_opener: callable | None = None,
) -> IO[Any]:
The most frequently used parameters are target_path, access_mode, and text_encoding:
target_path: The absolute or relative path to the target file.access_mode: A string defining the file access pattern, defaults to"r"(read-only). Common modes include:"r": Read-only mode, raises an error if the file does not exist"w": Write mode, creates the file if it does not exist, and truncates all existing content if the file already exists"a": Append mode, adds new content to the end of the file without modifying existing data"b": Binary mode, can be combined with other modes (e.g.,"rb","wb")"t": Text mode (default, can be omitted, e.g.,"rt","wt")"x": Exclusive creation mode, creates a new file and raises an error if the file already exists
text_encoding: Defines the character encoding for text mode operations, common values include"utf-8","ascii", and"latin-1". Defaults toNone, which uses the system's default encoding.
You must close the file handle after use via the close() method to release system resources. For example, working with a sample text file:
# Open a text file with UTF-8 encoding
sample_handle = open("mountain_village.txt", encoding="utf-8")
# Close the file handle to free resources
sample_handle.close()
- File Reading
To read a file, first open it in read-only ("r") mode:
file_location = "mountain_village.txt"
file_obj = open(file_location, "r", encoding="utf-8")
Python provides multiple built-in methods to read file content:
# Read the first 10 characters
print(f"First 10 characters: {file_obj.read(10)}")
# Read all remaining content in the file
print(f"Full file content: {file_obj.read()}")
# Read a single line of content
single_line = file_obj.readline()
print(f"Single line output: {single_line}")
print(f"Type of readline result: {type(single_line)}")
# Read all lines into a list of strings
all_lines = file_obj.readlines()
print(f"List of all lines: {all_lines}")
print(f"Type of readlines result: {type(all_lines)}")
# Iterate over the file object to read line-by-line
for line in file_obj:
print(line)
Two common issues arise with these methods:
- Unintended blank lines in output: This occurs because the original file contains newline characters, and the
print()function automaticalyl appends a newline to each output. - Sequential read behavior: Each read operation advances the internal file pointer, so subsequent reads start from the end of the previous read. Additionally, an open file handle will be locked by the Python process, preventing deletion, renaming, or movement until closed.
To avoid forgetting to call close(), Python provides the with context manager, which automatically closes the file handle once the nested code block finishes executing:
with open("test_read_file.txt", "r", encoding="utf-8") as active_file:
for line in active_file:
# Use rstrip() to remove trailing newlines for clean output
print(line.rstrip())
- File Writing
Core methods for file writing include:
write(content: str | bytes): Writes the specified content to the fileflush(): Forces buffered content to be written to the disk immediately
When writing to a file, content is first stored in an in-memory buffer until either flush() is called or the file handle is closed. Writing beahvior depends on the access mode:
"w"mode: Overwrites all existing content in the file"a"mode: Appends new content to the end of the file
Example overwrite write operation:
write_path = "demo_output.txt"
# Open file in overwrite mode
write_handle = open(write_path, "w", encoding="utf-8")
write_handle.write("Welcome to Python file operations!")
# Always close the handle to flush buffered content
write_handle.close()
Example append write operation:
append_path = "demo_output.txt"
# Open file in append mode
append_handle = open(append_path, "a", encoding="utf-8")
append_handle.write("\nHappy learning and coding!")
append_handle.close()