Skip to content
beginner

Basic File I/O in Python

Learning to work with files is a practical and essential skill for any beginner Python programmer. Whether you want to save notes, read a list of tasks, or…

Published 2026-05-11Updated 2026-05-159 min read

Learning to work with files is a practical and essential skill for any beginner Python programmer. Whether you want to save notes, read a list of tasks, or process data for a future job, file operations are everywhere. In this tutorial, you'll learn how to open, read, and write files in Python—step by step.

What Is File I/O?

File I/O stands for "File Input/Output." It means reading from or writing to files stored on your computer.

Why is this important? Most programs need to work with data that lives outside the code itself. For example:

  • Saving your game progress
  • Loading a list of names from a text file
  • Writing a log of your program’s activity

These are all file operations. Understanding Python file I/O helps you build programs that can remember things, process real-world data, and interact with other tools.

Types of Files You Can Work With

Files come in many forms, but as a beginner, you'll mostly work with two types:

  • Text files: Store data as readable text (like .txt or .csv files)
  • Binary files: Store data in a format meant for computers, not humans (like images or audio files)

We'll focus on text files for now, as they're the easiest to start with and cover most beginner needs.

Some common text file types:

  • .txt — Plain text files (notes, lists, etc.)
  • .csv — Comma-separated values, often used for spreadsheets or simple databases

Opening Files in Python

To work with a file, you must first open it. Python provides a built-in function called open() for this purpose.

Diagram comparing Python file open modes: read ('r'), write ('w'), append ('a'), and read/write ('r+'), showing permissions and effects on file content.

Comparison of Python file open modes: what each mode does, whether it requires the file to exist, and how it affects file contents. This helps you choose the correct mode for your task.

The basic way to open a file is:

file = open("example.txt", "r")

Here's what each part means:

  • "example.txt" is the name of the file you want to open.
  • "r" tells Python you want to read the file.

There are several modes you can use with open():

  • "r" — Read (default): Opens the file for reading. The file must exist.
  • "w" — Write: Opens the file for writing (and erases existing content or creates a new file).
  • "a" — Append: Opens the file for writing, but keeps existing content and adds new data to the end.
  • "r+" — Read and write: Opens the file for both reading and writing. The file must exist.

When you open a file, Python gives you a file object. You use this object to read or write data.

Quiz Question 1

Question: Which mode should you use with open() if you want to add new content to the end of a file without erasing its existing content?

  • A) 'r'
  • B) 'w'
  • C) 'a'

Reading from a File

Let's start by reading data from a file. Suppose you have a file called notes.txt with some text inside.

Reading the Entire File

You can read the whole file at once using the .read() method:

file = open("notes.txt", "r")
content = file.read()
print(content)
file.close()

This prints everything in notes.txt to the screen.

Reading Line by Line

Often, you'll want to process a file one line at a time. You can do this with a loop:

file = open("notes.txt", "r")
for line in file:
    print(line.strip())
file.close()

The .strip() method removes extra spaces or line breaks from each line.

Reading Only the First Line

If you want to read just the first line of a file, use the .readline() method:

file = open("notes.txt", "r")
first_line = file.readline()
print(first_line.strip())
file.close()

Reading All Lines into a List

If you want to read all lines at once and store them in a list, use .readlines():

file = open("notes.txt", "r")
lines = file.readlines()
for line in lines:
    print(line.strip())
file.close()

Writing to a File

Now let's write data to a file. This is how you can save information for later use.

Writing (Overwriting) a File

To write to a file, open it in "w" mode. Warning: This will erase any existing content in the file.

file = open("output.txt", "w")
file.write("Hello, world!\n")
file.write("This is my first file.\n")
file.close()

After running this, output.txt will contain your two lines of text.

Appending to a File

If you want to add new content without erasing what's already there, use "a" mode:

file = open("output.txt", "a")
file.write("Adding another line.\n")
file.close()

Now output.txt keeps the old content and adds your new line at the end.

Writing Multiple Lines

You can write multiple lines at once using .writelines() with a list of strings:

lines = ["First line\n", "Second line\n", "Third line\n"]
file = open("output.txt", "w")
file.writelines(lines)
file.close()

Quiz Question 2

Question: What's the difference between 'w' and 'a' modes when opening a file in Python?

  • A) 'w' overwrites the file, 'a' appends to it
  • B) 'w' reads the file, 'a' writes to it
  • C) 'w' is for text files, 'a' is for binary files

Closing Files and Why It Matters

Whenever you open a file, it's important to close it when you're done. This frees up resources and makes sure your data is saved properly.

You can close a file using:

file.close()

But there's an even safer (and easier) way: the with statement. This automatically closes the file for you, even if something goes wrong.

with open("notes.txt", "r") as file:
    content = file.read()
    print(content)
## File is now closed automatically

Using with is the recommended way for most file operations in Python.

Quiz Question 3

Question: Why is it recommended to use the 'with' statement when working with files in Python?

  • A) It automatically closes the file for you
  • B) It makes your code run faster
  • C) It lets you open multiple files at once
  • D) It prevents you from writing to the file

File Paths: Absolute vs. Relative

When opening files, you can use either a relative path (like "notes.txt") or an absolute path (like "C:/Users/you/Documents/notes.txt").

  • Relative path: Looks for the file in the same folder as your Python script.
  • Absolute path: Specifies exactly where the file is on your computer.

On Windows, remember to use double backslashes (\\) or raw strings (prefix with r) in file paths:

file = open(r"C:\\Users\\you\\Documents\\notes.txt", "r")

Common File I/O Errors and How to Avoid Them

Working with files isn't always smooth sailing. Here are some common issues beginners face—and how to handle them.

File Not Found

If you try to open a file that doesn't exist in read mode, Python will give you an error:

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

How to avoid: Make sure the file exists in the same folder as your Python script, or provide the correct path.

Permission Errors

Sometimes, you might not have permission to read or write a file (especially on shared or protected computers).

How to avoid: Make sure you have the right permissions, and try running your script in a folder where you have access.

Checking If a File Exists

If you're not sure if a file exists, you can check first using Python's os.path.exists() function:

import os

if os.path.exists("notes.txt"):
    with open("notes.txt", "r") as file:
        print(file.read())
else:
    print("File not found.")

Quiz Question 4

Question: What happens if you try to open a file for reading ('r') and the file does not exist?

  • A) Python creates a new empty file
  • B) Python gives a "FileNotFoundError"
  • C) Python ignores the error and continues

Practice: Simple File I/O Exercises

The best way to learn is by doing! Here are a few simple exercises to try on your own.

  1. Read a File:
    Create a text file called mydata.txt with a few lines of text. Write a Python script that reads and prints each line.

  2. Write to a File:
    Write a script that asks the user for their name and saves it to a file called names.txt.

  3. Append Data:
    Modify your script to add a new name to names.txt each time you run it, instead of overwriting the file.

  4. Test Safely:
    If you're worried about overwriting important files, practice with new files or use files with "test" in the name.

Quiz Question 5

Question: Which method reads all lines from a file and returns them as a list?

  • A) .read()
  • B) .readline()
  • C) .readlines()
  • D) .writelines()

Wrapping Up

You've just learned the basics of Python file I/O: how to open, read, and write files. These skills are the foundation for many real-world programming tasks, from data analysis to web development.

Keep practicing with your own files. The more you experiment, the more confident you'll become. Soon, reading and writing files in Python will feel like second nature!


Quiz Answer Key

Question 1

Correct answer: C) 'a'

Explanation: The 'a' mode stands for append, which adds new data to the end of the file without deleting what's already there.

Question 2

Correct answer: A) 'w' overwrites the file, 'a' appends to it

Explanation: 'w' mode erases the file's existing content before writing, while 'a' mode keeps the existing content and adds new data to the end.

Question 3

Correct answer: A) It automatically closes the file for you

Explanation: The 'with' statement ensures that the file is properly closed after you're done, even if an error occurs.

Question 4

Correct answer: B) Python gives a "FileNotFoundError"

Explanation: If you try to open a file for reading and it doesn't exist, Python will raise a FileNotFoundError.

Question 5

Correct answer: C) .readlines()

Explanation: The .readlines() method reads all lines from a file and returns them as a list of strings.

Practical resource

Want a more structured Python path?

Use the Python Starter Pack to turn scattered tutorials into a focused practice path.

View the bundle
Coming soon

Python Starter Pack

A compact LearnPyFast PDF pack covering what Python is, installation, your first program, running Python code, and Python versions.

$9
PDF BundleTopic PackPythonBeginner
  • 5 curated chapters
  • Enhanced PDF edition with bundle-only learning guidance
  • Offline-friendly format for focused review
  • Source article links for future online updates

Coming soon

Related sites

Continue beyond Python

Explore related Worldmonger sites when you want to move from Python basics into JavaScript or LLM application building.

JavaScript tutorialstutorial

LearnJSFast

Beginner-friendly JavaScript tutorials for practical web development and self-taught developers.

JavaScriptFrontendWeb development
Visit LearnJSFast
LLM tutorialstutorial

LearnLLMFast

Practical LLM tutorials for builders who want to understand prompting, workflows, agents, and AI applications.

LLMAIBuilders
Visit LearnLLMFast

Keep learning

Related tutorials

Continue with nearby Python topics and beginner-friendly explanations.

beginner7 min read

Dictionaries in Python

Have you ever needed to match a name to a phone number, or a word to its definition? This idea of connecting one thing to another is everywhere in daily…

Read tutorial
beginner7 min read

Lists in Python

If you’ve ever made a grocery list, kept track of your favorite songs, or collected numbers for a project, you already understand the need to store…

Read tutorial