open() / file.read() / file.write()
These are the basic operations for reading and writing text files. Use the open() function to open a file, then use read and write methods to process data.
Syntax
# Open a file for reading or writing (the with statement closes it automatically).
with open(file_path, mode, encoding='utf-8') as f:
content = f.read() # Read the entire contents as a string.
line = f.readline() # Read one line at a time.
line_list = f.readlines() # Read all lines as a list.
f.write(text) # Write text to the file.
f.writelines(line_list) # Write multiple lines at once.
Common Modes and Methods
| Mode / Method | Description |
|---|---|
| 'r' (read) | Opens the file in read mode. Raises a FileNotFoundError if the file does not exist. This is the default when no mode is specified. |
| 'w' (write) | Opens the file in write mode. Overwrites the contents if the file already exists. Creates a new file if it does not exist. |
| 'a' (append) | Opens the file in append mode. Adds new content to the end of any existing content. |
| 'x' (exclusive creation) | Creates a new file and opens it in write mode. Raises a FileExistsError if the file already exists. |
| f.read() | Returns the entire contents of the file as a single string. |
| f.readline() | Returns one line of text. Each subsequent call returns the next line. |
| f.readlines() | Returns all lines as a list. Each element includes the newline character. |
| f.write(text) | Writes text to the file. Newline characters are not inserted automatically. |
| f.writelines(list) | Writes a list of strings to the file at once. Newline characters are not inserted automatically. |
Sample Code
# Write text to a file.
with open('memo.txt', 'w', encoding='utf-8') as f:
f.write('Line 1 text.\n')
f.write('Line 2 text.\n')
# Read the entire contents of the file.
with open('memo.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content) # Prints the entire contents of the file.
# Read line by line (suitable for large files).
with open('memo.txt', 'r', encoding='utf-8') as f:
for line in f:
print(line.rstrip()) # Prints each line without the trailing newline.
# Use readlines() to get all lines as a list.
with open('memo.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
print(f'{len(lines)} lines found.')
print(lines[0].strip()) # Prints the content of the first line.
# Use writelines() to write multiple lines at once.
lines_to_write = ['apple\n', 'banana\n', 'cherry\n']
with open('fruits.txt', 'w', encoding='utf-8') as f:
f.writelines(lines_to_write)
# Use append mode ('a') to add content to the end of the file.
with open('memo.txt', 'a', encoding='utf-8') as f:
f.write('Appended line.\n')
# Handle the error when the file does not exist.
try:
with open('nonexistent_file.txt', 'r', encoding='utf-8') as f:
content = f.read()
except FileNotFoundError:
print('File not found.')
Notes
It is recommended to use the with open(...) as f: syntax for file operations. The with statement automatically calls f.close() when the block exits, ensuring the file is properly closed even if an exception occurs.
When reading or writing files that contain multibyte characters, always specify encoding="utf-8" explicitly. On Windows, the default encoding varies by environment, which can cause garbled text or exceptions if omitted.
The modern path library pathlib lets you write concise code such as Path("memo.txt").read_text(encoding="utf-8"). See pathlib.Path() for details.
If you find any errors or copyright issues, please contact us.