Manipulating Files

Lesson 14 of 16 • 10 XP

Keep your place in this quest

Log in or sign up for free to subscribe, follow lesson progress, and access more learning content.

File manipulation is a common task in many Python programs.
Whether you’re reading a data file, saving a configuration, or writing a log, interacting with the file system allows your programs to store and retrieve information long after they’ve stopped running.

In this lesson, we’ll explore the basics of reading and writing files in Python.
You’ll learn how to create, open, edit, and close files, as well as a few useful tricks like checking if a file exists before using it.


Creating and Opening Files

Before you can read or write to a file, you need to open it in the correct mode.
The mode tells Python what you intend to do with the file:

  • 'r' → Read (file must exist)
  • 'w' → Write (creates or overwrites the file)
  • 'a' → Append (add to the end of the file)
  • + → Add read/write capability to the mode ('w+', 'r+', 'a+')

Example — creating and opening a file in write mode:

file = open('file.txt', 'w+')
# ...
file.close()

Here we:

  1. Open (or create) file.txt in write-and-read mode (w+).
  2. Get back a file object we can use to write to or read from.
  3. Close the file when we’re done to free resources.
TIP: Always close files after using them — better yet, use a "with" statement so Python closes them automatically.

Writing to Files

Use .write() to send text into a file. It accepts a string and writes it exactly as given.

Example:

file = open('file.txt', 'w+')
file.write('Hello, world!\n')
file.close()

Here:

  • We overwrite (or create) file.txt.
  • We add the text "Hello, world!" followed by \n (newline) so the next write starts on a new line.
Note: If you open a file in 'w' mode, its previous contents are erased before writing.

Reading from Files

Use .read() to get the entire file content as a string.

Example:

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

This:

  • Opens file.txt in read mode.
  • Reads everything into the variable content.
  • Prints it out.

Checking if a File Exists

Sometimes, trying to open a non-existent file in read mode will cause an error. We can avoid that by checking first using the os module.

Example:

import os

if os.path.exists('file.txt'):
    file = open('file.txt', 'r')
    print(file.read())
    file.close()
else:
    print('File does not exist.')

This:

  • Uses os.path.exists() to check if the file is there.
  • Reads and prints its content if found.
  • Otherwise, displays a message.

Wrapping Up

With these basics, you can: • Create and open files. • Write and read data. • Safely check before accessing a file.

In the next lesson, we’ll cover error handling, so your programs keep running smoothly even when file operations go wrong.