Skip to content

File Handling

You will write, read, append, and loop through text files safely.

10 min read 10 quiz questions

Open a file

A file lets your program keep text after it finishes. Use open() to access a file, then use with so Python closes it for you.

These examples use demo.txt in the current directory, which works in the browser sandbox.

ModeMeaningUse
'r'Read an existing fileRead text
'w'Write and replace existing contentCreate a fresh file
'a'Append to the endAdd another line
'x'Create a new file onlyAvoid overwriting
'r+'Read and writeUpdate a file
Example: write a file with with open()
with open("demo.txt", "w") as file:
    file.write('First line\nSecond line\n')

print('Saved demo.txt')

The 'w' mode creates the file if needed. If it already exists, its old contents are replaced. The with block closes the file when the indented code ends.

Read file contents

Example: read the whole file
with open('demo.txt', 'w', encoding='utf-8') as file:
    file.write('First line\nSecond line\n')

with open('demo.txt', 'r', encoding='utf-8') as file:
    contents = file.read()

print(contents, end='')

read() returns the entire file as one string. Here end='' avoids adding an extra blank line because the file text already ends with a newline.

Reading lines from files

Example: readline(), readlines(), and a loop
with open('demo.txt', 'w', encoding='utf-8') as file:
    file.write('First line\nSecond line\nThird line\n')

with open('demo.txt', 'r', encoding='utf-8') as file:
    first_line = file.readline().strip()
    remaining_lines = file.readlines()

print(first_line)
for line in remaining_lines:
    print(line.strip())

readline() gets one line. readlines() gets the remaining lines as a list. You can also loop directly over a file to handle one line at a time.

Example: append, then read back
with open('demo.txt', 'w', encoding='utf-8') as file:
    file.write('First line\nSecond line\n')

with open('demo.txt', 'a', encoding='utf-8') as file:
    file.write('Third line\n')

with open('demo.txt', 'r', encoding='utf-8') as file:
    for line in file:
        print(line.rstrip())

Key points

  • Use with open() so files close automatically.
  • The w mode replaces old content.
  • read() returns the entire file as one string.
  • readline() and readlines() work with lines.
  • Use a mode to control how you access a file.

Worked example

Keep a guest list on disk: write three names, close, then read them back.

Example
with open("guests.txt", "w") as file:
    file.write("Mim\nRafi\nJoe\n")

with open("guests.txt") as file:
    print(file.read())

How it works, step by step

  1. "w" mode creates/truncates the file; write() adds text.
  2. with closes the file automatically, even on errors.
  3. Reading with no mode defaults to "r".

References & Further Reading

Related entries from PyLabs's own reference library.

  • open() (Open a file so you can read from it or write to it.)
  • read() (Read at most size characters or bytes from the file.)
  • write() (Write a string or bytes to the file stream.)
  • close() (Flush and close the open file handle.)

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Practice exercise

Not passed yet

Write Hello file! followed by a newline to demo.txt. Then read the file and print its contents without adding an extra newline.

# Write your code below
Want another challenge on this module? More coding practice

Check yourself

File Handling quiz

10 questions. You get instant feedback per question, and the timer starts when you press the button.

Lesson incomplete

Not completed

Create an ID or sign in to save lesson completion across devices.

Create ID to save
Module lesson progress0/5 complete
Module cheat sheet