Skip to content
PythonModules, Files, and Errorsbeginner22 min read

Reading and Writing Text Files

Learn to open, read, write, append, and safely manage text files using Python's file-handling tools.

In this lesson, you will learn

  • ✓Explain why programs use files to store data beyond a single execution.
  • ✓Open text files using open() and select appropriate file modes.
  • ✓Read file contents using read(), readline(), and line-by-line iteration.
  • ✓Write and append text while understanding how file modes affect existing content.
  • ✓Use with statements to close files automatically and specify text encoding.
  • ✓Use pathlib's read_text() and write_text() methods for simple file operations.
  • ✓Recognize common file-handling errors and choose appropriate solutions.

1. Why do programs use files?

A variable stores a value while a program is running, but ordinary in-memory variables do not automatically preserve that value after the program terminates. A file lets a program store data outside its running process so it can be read again later.

A text file stores characters that can be decoded into text. Examples include .txt files, simple configuration files, and application logs. This lesson focuses on text files rather than binary files such as images or audio.

Python offers more than one way to work with text files. The built-in open() function returns a file object with methods such as read(), readline(), and write(). The pathlib.Path class also offers convenient methods such as read_text() and write_text().

Reading and writing are different operations. Reading retrieves existing content; writing can create a file or replace its existing content depending on how the file is opened. Appending adds content to the end of a file.

Create and read a text file with pathlib

Create and read a text file with pathlib
python
from pathlib import Path
 
path = Path('note.txt')
path.write_text('Hello, Python!', encoding='utf-8')
content = path.read_text(encoding='utf-8')
print(content)
Output
Hello, Python!

Path('note.txt') represents a path named note.txt in the current working directory. write_text() writes the supplied text to the file, creating it if necessary and replacing existing content if the file already exists. encoding='utf-8' specifies how Python encodes and decodes the text. read_text() reads the file's text and returns it as a string. print() displays the string. This example creates or modifies a real file in the current working directory.

Note

The output above is the text printed by the program. The file-writing operation itself does not automatically print the content.

2. Opening a file with open()

The built-in open() function opens a file and returns a file object. You can call methods on that object to read or write data.

The simplest form is open('filename.txt', 'r'), where 'r' is the mode. For text files, Python uses text mode by default. You can explicitly specify encoding='utf-8' to make the intended text encoding clear.

The mode determines what you can do with the file. Choose it carefully because some modes can destroy existing content.

Common modes include:

- 'r': read an existing file. Opening a missing file raises FileNotFoundError.

- 'w': write to a file, creating it if necessary and truncating an existing file.

- 'a': append to the end of a file, creating it if necessary.

- 'x': create a new file and fail if that path already exists.

Modes can be combined with other options for specific needs, but these four are sufficient for many beginner text-file tasks.

Open a file and read its contents

Open a file and read its contents
python
with open('message.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
Output
Welcome to Python!

This example assumes message.txt already exists and contains Welcome to Python! without an additional newline. open() opens the file in read mode. The name file refers to the returned file object inside the with block. read() reads the remaining contents and returns them as a string. The output depends on the file's actual contents. If the file is missing, Python raises FileNotFoundError instead of printing the shown result.

Caution

Opening an existing file in 'w' mode erases its previous contents before writing the new text. Use 'a' when you want to preserve existing content and add more text.

3. Why use a with statement?

Files are operating-system resources. After your program finishes using a file, the file should be closed so that its resources can be released and buffered data can be handled correctly.

A with statement uses a context manager to manage the file's lifetime. When execution leaves the with block, Python closes the file, including when an exception occurs inside the block.

This is generally safer and clearer than opening a file and relying on a later manual close() call.

Indentation defines the with block. Statements indented beneath with run while the file is open; statements after the block run after the file has been closed.

Automatically close a file

Automatically close a file
python
with open('greeting.txt', 'w', encoding='utf-8') as file:
file.write('Hello')
 
print(file.closed)
Output
True

The file is opened inside the with statement. file.write('Hello') writes five characters to the file. When execution leaves the block, the context manager closes the file. file.closed is True after the block, so the final print() displays True. The file object still exists as a Python object, but its file is no longer open for ordinary reading or writing through that object.

Note

Prefer with open(...) as file: for ordinary file operations. You usually do not need to call file.close() yourself when using this pattern.

4. Reading file contents

A file object provides several ways to read text. The best method depends on how much data you need and how you want to process it.

read() reads the remaining content and returns it as a string. With no size argument, it reads to the end of the file. With a size argument, it reads up to that many characters in text mode.

readline() reads one line at a time. A returned line normally includes its newline character when one is present in the file.

readlines() returns a list containing the remaining lines. For large files, iterating directly over the file is generally more memory-efficient than loading every line into a list.

After reading reaches the end of a file, another read() normally returns an empty string. Reading methods also advance the file position, so a second read() does not automatically start from the beginning.

Read the entire file

Read the entire file
python
from io import StringIO
 
with StringIO('Python is fun.') as file:
text = file.read()
print(text)
print(repr(file.read()))
Output
Python is fun. ''

The first read() returns the entire string because the stream starts at the beginning. After the first read(), the file position is at the end. The second read() returns an empty string. repr() displays the empty string as two quotation marks, making the value visible.

5. Writing and appending text

The write() method writes a string to a writable text file. It returns the number of characters written and does not add a newline automatically.

Use '\n' when you want a newline between text records. The conventional newline character may be translated according to the platform and text-file settings.

The 'w' mode replaces existing file content. The 'a' mode appends new text to the end of the file. Both modes create the file if it does not exist.

Appending does not automatically insert a newline before the new text. If the existing file does not end with a newline, the appended text may appear immediately after its last character.

Write multiple lines

Write multiple lines
python
from io import StringIO
 
with StringIO() as file:
file.write('First line\n')
file.write('Second line\n')
print(file.getvalue(), end='')
Output
First line Second line

The first write() stores First line followed by a newline character. The second write() stores Second line followed by another newline character. getvalue() returns the complete contents of the in-memory stream. end='' prevents print() from adding an additional newline after the stored content. StringIO keeps this example in memory; no disk file is created.

Caution

Be deliberate when choosing between 'w' and 'a'. The former truncates existing content; the latter preserves existing content and adds new text at the end.

6. Using pathlib read_text() and write_text()

For straightforward text-file tasks, pathlib.Path offers read_text() and write_text(). These methods handle opening and closing the file internally, so you do not need to write an explicit with open(...) block for simple operations.

read_text(encoding='utf-8') reads the file and returns its contents as a string. write_text(text, encoding='utf-8') writes text to the path and creates the file if needed, replacing existing content.

Use path.open() when you need file modes such as append, want to process a file incrementally, or need access to file-object methods. Use read_text() and write_text() when reading or writing an entire small text file is sufficient.

These methods still interact with the real filesystem. A missing file, an invalid path, insufficient permissions, or a decoding problem can cause an exception.

Write and read text with pathlib

Write and read text with pathlib
python
from pathlib import Path
 
path = Path('practice.txt')
path.write_text('Practice makes progress.', encoding='utf-8')
content = path.read_text(encoding='utf-8')
print(content)
Output
Practice makes progress.

Path represents the target file path. write_text() writes the complete string and creates the file if necessary. read_text() retrieves the stored text as a string. Both methods receive the same encoding, UTF-8. The code overwrites practice.txt if it already exists.

Note

read_text() and write_text() are convenient for entire files, but reading a very large file all at once can consume substantial memory. Use a file object and process it incrementally when appropriate.

7. Encoding, file paths, and common errors

Text files contain encoded bytes. When Python reads a text file, it decodes those bytes into characters; when it writes text, it encodes characters into bytes. Specifying encoding='utf-8' makes the intended encoding explicit and helps programs behave consistently across environments.

A relative path such as 'notes.txt' is resolved from the process's current working directory, which is not necessarily the directory containing the Python source file. If a program cannot find a file, check its path and working directory before assuming the file does not exist.

FileNotFoundError commonly occurs when read mode is used for a path that does not exist. PermissionError can occur when the operating system denies access. UnicodeDecodeError can occur when the file's bytes cannot be decoded using the selected encoding.

Use exceptions deliberately. For example, catching FileNotFoundError can be appropriate when a missing file has a defined fallback. Avoid a broad except block that silently hides unrelated programming errors.

The 'x' mode can be useful when a program must create a new file without overwriting an existing one. If the path already exists, opening in 'x' mode raises FileExistsError.

Handle a missing file

Handle a missing file
python
from pathlib import Path
 
path = Path('missing-note.txt')
 
try:
content = path.read_text(encoding='utf-8')
except FileNotFoundError:
print('File not found')
else:
print(content)
Output
File not found

This example assumes missing-note.txt does not exist in the current working directory. read_text() raises FileNotFoundError when the target file is missing. The except block handles that specific error and prints a helpful message. The else block runs only when the try block completes without an exception. If the file exists, its contents are printed instead.

Caution

Examples that create, overwrite, or append to files have side effects. Use a suitable test directory and avoid choosing an existing important file as a practice target.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Opening a missing file in 'r' mode and expecting Python to create it.

Why it happens: Read mode expects the file to exist and raises FileNotFoundError if it does not; use an appropriate creation or write mode when creation is intended.

Incorrect Approach
script.py
python
Opening a missing file in 'r' mode and expecting Python to create it.
Correct Solution
script.py
python
Read mode requires an existing file. Use 'w', 'a', or 'x' when creating a file is intended, while accounting for their different behaviors.

Key takeaway: Read mode requires an existing file. Use 'w', 'a', or 'x' when creating a file is intended, while accounting for their different behaviors.

#2 Using 'w' mode when existing content must be preserved.

Why it happens: Write mode truncates an existing file, so use append mode or another strategy when previous content must be preserved.

Incorrect Approach
script.py
python
Using 'w' mode when existing content must be preserved.
Correct Solution
script.py
python
Use 'a' to append, or read and deliberately update the content using an appropriate strategy.

Key takeaway: Use 'a' to append, or read and deliberately update the content using an appropriate strategy.

#3 Assuming write() adds a newline automatically.

Why it happens: write() writes exactly the supplied text and does not add a newline unless the string includes one.

Incorrect Approach
script.py
python
Assuming write() adds a newline automatically.
Correct Solution
script.py
python
Include '\n' explicitly when a line break is required.

Key takeaway: Include '\n' explicitly when a line break is required.

#4 Opening files without specifying an encoding.

Why it happens: The default text encoding can vary by environment; specifying encoding="utf-8" improves portability for text files.

Incorrect Approach
script.py
python
Opening files without specifying an encoding.
Correct Solution
script.py
python
For ordinary text files, specify encoding='utf-8' unless the file format requires another known encoding.

Key takeaway: For ordinary text files, specify encoding='utf-8' unless the file format requires another known encoding.

#5 Forgetting to close files.

Why it happens: Files should be closed so buffers are flushed and operating-system resources are released; a with statement handles this reliably.

Incorrect Approach
script.py
python
Forgetting to close files.
Correct Solution
script.py
python
Use with open(...) as file: so the file is closed when the block exits.

Key takeaway: Use with open(...) as file: so the file is closed when the block exits.

#6 Calling read() repeatedly and expecting to reread the same content.

Why it happens: read() advances the file cursor, so a second read usually starts at the current end; seek(0) or reopen the file to read from the beginning.

Incorrect Approach
script.py
python
Calling read() repeatedly and expecting to reread the same content.
Correct Solution
script.py
python
The file position advances after reading. Reopen the file or seek back to the beginning when appropriate.

Key takeaway: The file position advances after reading. Reopen the file or seek back to the beginning when appropriate.

#7 Assuming a relative path is resolved from the source file's directory.

Why it happens: Relative paths are resolved from the process's current working directory, which may differ from the directory containing the source file.

Incorrect Approach
script.py
python
Assuming a relative path is resolved from the source file's directory.
Correct Solution
script.py
python
Relative paths are normally resolved from the current working directory. Check the working directory and path when a file cannot be found.

Key takeaway: Relative paths are normally resolved from the current working directory. Check the working directory and path when a file cannot be found.

#8 Catching every exception without reporting or handling the cause.

Why it happens: Catching every exception can hide the actual problem; catch expected exceptions and report or handle them deliberately.

Incorrect Approach
script.py
python
Catching every exception without reporting or handling the cause.
Correct Solution
script.py
python
Handle specific expected exceptions, such as FileNotFoundError, and allow unexpected errors to remain visible during development.

Key takeaway: Handle specific expected exceptions, such as FileNotFoundError, and allow unexpected errors to remain visible during development.

#9 Calling read() twice and expecting the same text both times.

Why it happens: The file cursor advances after read(), so a repeated call may return an empty string unless the cursor is reset.

Incorrect Approach
script.py
python
Calling read() twice and expecting the same text both times.
Correct Solution
script.py
python
Reading advances the file position. Reopen the file or use seek(0) on a suitable seekable file to return to the beginning.

Key takeaway: Reading advances the file position. Reopen the file or use seek(0) on a suitable seekable file to return to the beginning.

#10 Assuming readline() removes the newline character.

Why it happens: readline() usually includes the line-ending character when one exists; strip or rstrip it only when that behavior is desired.

Incorrect Approach
script.py
python
Assuming readline() removes the newline character.
Correct Solution
script.py
python
A line normally includes its newline if one is present. Use strip() or rstrip('\n') when removing line endings is appropriate.

Key takeaway: A line normally includes its newline if one is present. Use strip() or rstrip('\n') when removing line endings is appropriate.

#11 Loading a very large file with readlines() when only one line at a time is needed.

Why it happens: readlines() loads all lines into memory; iterate over the file object when processing a large file line by line.

Incorrect Approach
script.py
python
Loading a very large file with readlines() when only one line at a time is needed.
Correct Solution
script.py
python
Iterate over the file object to process lines incrementally.

Key takeaway: Iterate over the file object to process lines incrementally.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is the difference between read(), readline(), and readlines()?
Answer:
read() returns the remaining content as a string, readline() returns one line at a time, and readlines() returns a list of the remaining lines. For large files, iterating directly over the file is often preferable because it avoids loading every line into a list.
Q2:What is the difference between 'w', 'a', and 'x' file modes?
Answer:
'w' creates a file or truncates an existing one, 'a' creates a file if needed and appends to its end, and 'x' creates a new file but raises FileExistsError if the path already exists.
Q3:Why should files be opened with a context manager?
Answer:
A with statement ensures that the file is closed when execution leaves the block, including when an exception occurs. This makes resource management more reliable.
Q4:What is the difference between open() and pathlib's read_text() and write_text()?
Answer:
open() returns a file object and supports different modes and incremental operations. Path.read_text() and Path.write_text() are convenient methods for reading or writing an entire text file without manually managing the file object's lifetime.
Q5:Why specify encoding='utf-8'?
Answer:
Encoding determines how text is converted between characters and bytes. Specifying UTF-8 makes the intended encoding explicit and reduces dependence on environment-specific defaults.
Q6:What happens if read() is called twice without repositioning the file?
Answer:
The first call advances the file position. A second call reads from the new position and returns an empty string if the first call already consumed the entire file. Reopen the file or use seek(0) on a suitable seekable stream to read from the beginning again.
Q7:How would you handle a file that might not exist?
Answer:
Use an appropriate path and handle FileNotFoundError when a missing file is an expected condition. Decide whether to report the problem, use a fallback, or create the file. Avoid silently suppressing unrelated exceptions.

Key takeaways

  • Files allow programs to store and retrieve data beyond a single execution.
  • open() returns a file object, and the mode determines whether the file is read, replaced, appended to, or created exclusively.
  • Use with statements to manage file resources and close files automatically.
  • read(), readline(), and readlines() have different return values and memory-use characteristics.
  • write() does not add a newline automatically.
  • Path.read_text() and Path.write_text() are convenient for reading or writing entire text files.
  • Specify an appropriate text encoding, commonly UTF-8.
  • Relative paths are resolved from the current working directory, and file operations can raise exceptions.
  • Test file-handling examples in a suitable directory because writing operations can create or overwrite real files.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: