How to read and write files in Python

Once you understand functions and basic error handling, the next major step in beginner Python is working with files. So far, most examples in the course have used values stored directly in variables while the program is running. That is useful for learning logic, but real programs often need to work with data outside the script itself. You may want to read text from a file, save notes, store results, create logs, or process lists of values from an external source. This is exactly where file handling becomes important.

Python makes basic file operations relatively simple, which is one reason it is so popular for automation, scripting, and practical utility programs. A beginner can quickly learn how to open a file, read its contents, write new data, and close it safely. At the same time, file handling introduces real-world concerns such as missing files, overwriting content, and choosing the correct mode for each task.

This lesson explains how to read and write files in Python in a clear, beginner-friendly way. You will learn what file handling means, how open() works, what the main file modes are, how to read and write text files, how with open() helps, what common beginner mistakes look like, and why file operations are such an important part of practical Python programming.

What file handling means in Python

File handling means working with files stored on your computer or system. In Python, this usually includes tasks such as:

  • opening a file
  • reading its contents
  • writing new content
  • adding content to an existing file
  • processing text line by line
  • closing the file safely

For beginners, the most common first examples involve plain text files such as:

  • notes
  • logs
  • saved results
  • small data lists
  • configuration-style text

Instead of keeping all data only in memory while the script runs, file handling lets the program interact with persistent data that remains available after the script ends.

Why file handling matters

Without file handling, many beginner programs remain temporary. They can calculate or print results, but once the program stops, the data is gone unless it was shown on screen and manually copied somewhere else.

With file handling, Python programs can:

  • save results for later
  • read data created earlier
  • build text-based logs
  • load settings
  • process lists of values from files
  • automate repetitive document tasks
  • work with external content in a structured way

This makes file handling one of the first truly practical skills in Python. It is the point where the program starts interacting with the outside world in a persistent way.

The open() function in Python

The main function used for file handling is open().

Basic example:

file = open(“example.txt”, “r”)

This tells Python to open a file called example.txt in read mode.

The two most important parts here are:

  • the file name or file path
  • the file mode

In this example:

  • "example.txt" is the file name
  • "r" means read mode

Opening a file gives you a file object, which you can then use to read or write data.

File modes in Python

When opening a file, you usually specify a mode that tells Python what you want to do with it.

The most important beginner file modes are:

  • "r" → read
  • "w" → write
  • "a" → append
  • "x" → create
  • "rb" → read in binary mode
  • "wb" → write in binary mode

For this beginner chapter, the main text-focused modes are r, w, and a.

Read mode: “r”

This opens a file for reading.

file = open(“example.txt”, “r”)

If the file does not exist, Python raises an error.

Write mode: “w”

This opens a file for writing.

file = open(“example.txt”, “w”)

Important beginner warning:

write mode replaces the existing file content

If the file already has text inside, using "w" will overwrite it.

Append mode: “a”

This opens a file for adding new content at the end.

file = open(“example.txt”, “a”)

This is useful when you want to keep the old content and add more text after it.

Reading a file in Python

To read a text file, you usually open it in "r" mode and then call a reading method.

Example:

file = open(“example.txt”, “r”)
content = file.read()
print(content)
file.close()

This does four things:

  • opens the file
  • reads all content into a variable
  • prints it
  • closes the file

This is a valid beginner pattern, but there is a better and safer version using with open(), which we will cover shortly.

The read() method

The read() method reads the entire content of the file as one string.

Example file content:

Hello
Python file handling

Code:

file = open(“example.txt”, “r”)
content = file.read()
print(content)
file.close()

Output:

Hello
Python file handling

This is useful when you want all the text at once.

However, if the file is very large, reading the whole thing at once may not always be ideal. For beginner text files, though, read() is often fine.

Reading only part of a file

The read() method can also take a number, meaning “read this many characters.”

Example:

file = open(“example.txt”, “r”)
content = file.read(5)
print(content)
file.close()

If the file begins with:

Hello Python

then the output is:

Hello

This can be useful when you want only part of the content.

The readline() method

The readline() method reads one line at a time.

Example:

file = open(“example.txt”, “r”)
line1 = file.readline()
line2 = file.readline()print(line1)
print(line2)

file.close()

This is useful when you want to process a file line by line.

A typical beginner use case is reading structured text where each line has separate meaning.

The readlines() method

The readlines() method reads all lines and returns them as a list.

Example:

file = open(“example.txt”, “r”)
lines = file.readlines()
print(lines)
file.close()

If the file contains:

apple
banana
orange

the output may look like:

[‘apple\n, ‘banana\n, ‘orange\n]

Notice the \n characters. These represent line breaks.

This is useful because it connects file handling with lists, which you already learned earlier in the course.

Looping through a file line by line

A very common and useful Python pattern is looping through a file directly.

Example:

file = open(“example.txt”, “r”)

for line in file:
print(line)

file.close()

This reads each line one at a time.

A cleaner version often removes the trailing newline using strip():

file = open(“example.txt”, “r”)

for line in file:
print(line.strip())

file.close()

This is one of the most practical beginner patterns for file reading.

Why closing a file matters

When you open a file, the system gives your program access to it. Once you are finished, the file should be closed properly.

Example:

file = open(“example.txt”, “r”)
content = file.read()
file.close()

Closing matters because it:

  • releases system resources
  • ensures writing is finalized properly
  • avoids file access problems
  • keeps your code cleaner and safer

Beginners sometimes forget to close files, which is one reason with open() is the preferred approach.

The better way: with open()

The recommended beginner-friendly way to handle files is with open().

Example:

with open(“example.txt”, “r”) as file:
content = file.read()
print(content)

This is better because Python automatically closes the file when the block ends.

You do not need a separate file.close() line.

This is one of the most important file-handling habits to learn early.

Why with open() is better

Using with open() is better because it:

  • closes the file automatically
  • reduces the chance of forgetting cleanup
  • makes the code shorter
  • is considered more Pythonic
  • works well even if an error happens inside the block

That means beginners should usually prefer this pattern:

with open(“example.txt”, “r”) as file:
content = file.read()

instead of manual open/close patterns, unless there is a special reason not to.

Writing to a file in Python

To write to a file, open it in write mode "w" and use write().

Example:

with open(“example.txt”, “w”) as file:
file.write(“Hello from Python”)

This creates the file if it does not exist.
If it already exists, its previous content is replaced.

This is one of the most important beginner warnings in Python file handling:

"w" overwrites existing content

The write() method

The write() method writes a string to the file.

Example:

with open(“notes.txt”, “w”) as file:
file.write(“First line”)

If you want multiple lines, you need to include newline characters manually:

with open(“notes.txt”, “w”) as file:
file.write(“First line\n)
file.write(“Second line\n)
file.write(“Third line\n)

Without \n, the text will continue on the same line.

This is a common beginner issue.

Appending to a file

If you want to add content without deleting the old content, use append mode "a".

Example:

with open(“notes.txt”, “a”) as file:
file.write(“Another line\n)

This adds the new line to the end of the existing file.

Append mode is useful for:

  • logs
  • adding records
  • saving repeated results
  • keeping history instead of replacing it

The difference between write mode and append mode

This distinction is very important:

Write mode "w"

  • creates the file if needed
  • clears old content if the file already exists

Append mode "a"

  • creates the file if needed
  • keeps old content
  • adds new content at the end

Example:

with open(“example.txt”, “w”) as file:
file.write(“New content”)

This replaces old content.

Example:

with open(“example.txt”, “a”) as file:
file.write(\nMore content”)

This adds to the file.

Beginners should choose carefully depending on whether they want replacement or addition.

Writing multiple lines from a list

Since write() works with strings, writing multiple lines from a list often means looping.

Example:

fruits = [“apple”, “banana”, “orange”]

with open(“fruits.txt”, “w”) as file:
for fruit in fruits:
file.write(fruit + \n)

This is a very practical beginner example because it combines:

  • lists
  • loops
  • file writing

It also shows how earlier course topics connect naturally to file handling.

Reading lines into a list

File handling also works in the other direction. You can read file lines into a list.

Example:

with open(“fruits.txt”, “r”) as file:
lines = file.readlines()print(lines)

To remove the line breaks, you can process them:

with open(“fruits.txt”, “r”) as file:
lines = file.readlines()clean_lines = []

for line in lines:
clean_lines.append(line.strip())

print(clean_lines)

Output might be:

[‘apple’, ‘banana’, ‘orange’]

This is a good beginner pattern for simple file-based data loading.

File paths in Python

So far, the examples used simple file names like "example.txt". This usually works when the file is in the same folder as the Python script.

You can also use a path:

with open(“data/example.txt”, “r”) as file:
content = file.read()

Or an absolute path:

with open(“C:/Users/Name/Documents/example.txt”, “r”) as file:
content = file.read()

At beginner level, the most important thing is understanding that Python needs the correct file location. If the file is not where Python expects it, you get an error.

FileNotFoundError explained

One of the most common beginner file-handling errors is FileNotFoundError.

Example:

with open(“missing.txt”, “r”) as file:
content = file.read()

If missing.txt does not exist in the expected location, Python raises FileNotFoundError.

Safe version:

try:
with open(“missing.txt”, “r”) as file:
content = file.read()
print(content)
except FileNotFoundError:
print(“The file was not found”)

This is one of the most practical uses of error handling with files.

Encoding in Python file handling

Text files use an encoding, which is a system for representing characters. A common and beginner-friendly option is UTF-8.

You can specify it like this:

with open(“example.txt”, “r”, encoding=“utf-8”) as file:
content = file.read()
print(content)

And for writing:

with open(“example.txt”, “w”, encoding=“utf-8”) as file:
file.write(“Hello, világ”)

Using encoding="utf-8" is a good habit, especially when your text may contain accented or non-English characters.

Practical beginner examples

Example 1: Read an entire text file

with open(“example.txt”, “r”, encoding=“utf-8”) as file:
content = file.read()
print(content)

Example 2: Write text to a file

with open(“output.txt”, “w”, encoding=“utf-8”) as file:
file.write(“This was written by Python”)

Example 3: Append a new line

with open(“log.txt”, “a”, encoding=“utf-8”) as file:
file.write(“New log entry\n)

Example 4: Read line by line

with open(“example.txt”, “r”, encoding=“utf-8”) as file:
for line in file:
print(line.strip())

Example 5: Save a list to a file

items = [“red”, “green”, “blue”]

with open(“colors.txt”, “w”, encoding=“utf-8”) as file:
for item in items:
file.write(item + \n)

These examples cover the core beginner patterns for file reading and writing.

Common beginner mistakes with Python files

Several problems appear often when beginners first work with files.

Forgetting that “w” overwrites content

Example:

with open(“notes.txt”, “w”) as file:
file.write(“New text”)

If notes.txt already had important content, it is now replaced.

Beginners often expect writing to add content automatically, but that is not how "w" works.

Forgetting newline characters when writing multiple lines

Example:

with open(“notes.txt”, “w”) as file:
file.write(“Line one”)
file.write(“Line two”)

This produces:

Line oneLine two

If you want separate lines, use \n.

Trying to read a file that does not exist

Example:

with open(“missing.txt”, “r”) as file:
content = file.read()

This causes FileNotFoundError.

Forgetting to use with open()

Manual opening works, but beginners often forget close(). That is why with open() is the safer default.

Confusing file content with file name

A file object is not the same as the content inside it.

Example:

with open(“example.txt”, “r”) as file:
print(file)

This prints information about the file object, not the actual file text.

To get the content, you need:

print(file.read())

Using the wrong mode

Trying to read in write mode or expecting write behavior in read mode leads to confusion.

Beginners should choose the mode deliberately:

  • r for reading
  • w for replacing with new text
  • a for adding new text

Combining files with loops and functions

File handling becomes especially useful when combined with earlier Python concepts.

Example with a function:

def save_message(message):
with open(“messages.txt”, “a”, encoding=“utf-8”) as file:
file.write(message + \n)save_message(“Hello”)
save_message(“Python”)

Example with a loop:

with open(“numbers.txt”, “w”, encoding=“utf-8”) as file:
for number in range(1, 6):
file.write(str(number) + \n)

These examples show that file handling is not isolated. It integrates naturally with the rest of Python.

Reading a file and processing its content

A file is often not just read for display. It is read so that the content can be processed.

Example:

with open(“fruits.txt”, “r”, encoding=“utf-8”) as file:
for line in file:
fruit = line.strip()
print(“Fruit:”, fruit)

This demonstrates a realistic pattern:

  • read one line
  • clean it
  • use it in the program

This is a very common Python workflow in automation and text processing.

Why file handling is so useful in real Python scripts

File handling is one of the first Python skills that feels immediately practical outside tutorial code.

Real beginner-friendly use cases include:

  • saving notes
  • storing quiz results
  • writing logs
  • reading task lists
  • processing text reports
  • exporting generated data
  • saving user entries
  • reading configuration values

This is why file handling is such an important chapter in any beginner Python course. It turns short-lived scripts into tools that interact with persistent information.

Good beginner habits with file handling

A few habits make file-related code much safer and cleaner.

Prefer with open()

This avoids forgotten file closures and makes the code cleaner.

Use the correct file mode deliberately

Do not use "w" unless you really want to replace the old content.

Use UTF-8 encoding when working with text

This helps avoid character problems.

Print or inspect file content while learning

When unsure, read the content and display it so you can verify the result.

Use try and except when a file may not exist

This makes the program more user-friendly and robust.

Keep paths simple at first

When learning, it is easier to keep the file in the same folder as the script.

What you should understand before moving on

Before continuing to the next lesson, you should be comfortable with the following:

  • open() is used to work with files
  • file modes such as r, w, and a control how the file is used
  • read() reads the full file content
  • readline() reads one line
  • readlines() reads all lines into a list
  • write() writes text to a file
  • "w" overwrites old content
  • "a" adds new content without deleting old content
  • with open() is the preferred safe pattern
  • FileNotFoundError happens when a file cannot be found
  • encoding="utf-8" is a good habit for text files

If these ideas are clear, the next lesson on importing modules in Python will be easier, because file handling and modules are both part of writing more practical and reusable Python programs.

Reading and writing files in Python allows your programs to work with persistent data instead of only temporary variables. With open(), read(), write(), and the safer with open() pattern, a beginner can quickly start building scripts that save information, load text, process line-based data, and create useful outputs.

File handling is one of the most practical beginner Python skills because it connects the language to real tasks such as saving notes, reading data, writing logs, and automating text-based workflows. Once you understand the difference between reading, writing, and appending, and you know how to handle missing files safely, you have a strong foundation for many real-world Python projects.


Image(s) used in this article are either AI-generated or sourced from royalty-free platforms like Pixabay or Pexels.

This article may contain affiliate links. If you purchase through these links, we may earn a commission at no extra cost to you.

Weekly briefing

Get the weekly RF & IT briefing

Radio guides, RF calculators, AI, Windows, Linux and satellite communication explainers. One useful email per week. No spam.

Similar Posts