A Comprehensive Guide to File Input/Output in Python

Master file handling with clear-cut examples and best practices

Max N
3 min readApr 8, 2024
Photo by Arthur Mazi on Unsplash

Handling files is an essential aspect of programming. Whether you’re working on data analysis or building web applications, reading from and writing to files are common tasks. This guide will walk you through file input/output operations in Python using practical examples.

Opening Files

To work with files in Python, we need to open them first. The built-in open() function takes two arguments - the filename (or path), and the mode. There are several modes available such as 'r', 'w', 'a', etc., but let's focus on these three core ones:

  • ‘r’: Opens a file in read mode, used when only retrieving information. Raises an error if the file doesn’t exist.
file = open('example.txt', 'r')
  • ‘w’: Opens a file in write mode, erasing its previous content. If it didn’t exist before, creates one.
file = open('new_file.txt', 'w')
  • ‘a’: Appends to an existing file; otherwise, behaves similarly to ‘w’.
file = open('existing_file.txt', 'a')

Reading Data From Files

--

--

Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.